Learning Objectives
- Build a functional agent from scratch
- Define agent capabilities and constraints
- Test and validate agent behaviour
π― What You'll Learn: How to build a specialized agent that analyzes problems deeply
β±οΈ Time Required: 60 minutes
π¦ What You'll Build: A workingposition-risk-analyzeragent (or YOUR equivalent)
Riley's Journey Continues
In Lesson 2.1, Riley built her decision framework and identified her first agent candidate: analyzing why positions are at risk. Her weekly-margin-report skill flags at-risk positions, but it can't explain WHY.
Now she's ready to build the analyst she needs.
π¬ "My margin report tells me THAT 7 positions are at risk. But my VP always asks 'Why?' and 'What should we do about it?' I used to spend 2 hours manually researching each position. Today, I'm building an agent that does that analysis for me."
β Riley Harper
Where Riley is now:
weekly-margin-report skill identifying at-risk positionsposition-risk-analyzer agentBy the end of this lesson:
What We're Building in This Lesson
An agent is like hiring a specialist consultant with a specific brief. You define what they focus on, what tools they can use, and how they should work.
In this lesson:
π‘ A note on terminology: Anthropic's official Skilljar training calls these "subagents." This course uses "agents", same concept, same files, same behaviour. If you're cross-referencing Skilljar material, the terms are interchangeable.
Key Concept: Agent Anatomy
What Is an Agent Really?
An agent is a specialized Claude instance with:
The Agent File Structure
---
name: agent-name
description: What this agent does and when to use it
author: Your Name
version: 1.0
---
# Agent Name
## Role
[Who this agent is - their expertise and perspective]
## Mission
[What they're trying to accomplish]
## Process
[How they approach problems]
## Output Format
[What their deliverable looks like]
## Examples
[Sample inputs and outputs]
Skills vs. Agents: Side-by-Side
| Aspect | Skill | Agent |
|---|---|---|
| File location | .claude/skills/ | .claude/agents/ |
| Context | Uses current conversation | Fresh, isolated context |
| Invocation | Automatic or /skill-name | Automatic, or ask Claude for it by name |
| Best for | Repeatable tasks | Analysis & research |
| Think of it as | Company SOP | Specialist consultant |
Exercise: Build Your First Agent
β±οΈ Total Time: 50 minutes
What You'll Build
π§ A working agent that performs deep analysis on a problem from your decision framework.
Step 1: Create Your Agent Folder
β±οΈ Time: 5 minutes
What you're doing:
Setting up the agents folder. Note one difference from skills: a skill is a folder with a SKILL.md inside, but an agent is a single Markdown file placed directly in .claude/agents/.
Command to run:
mkdir -p .claude/agents
Riley's structure:
.claude/
βββ skills/
β βββ weekly-margin-report/
β βββ SKILL.md
βββ agents/
βββ position-risk-analyzer.md β We're creating this
Your command:
mkdir -p .claude/agents
Naming conventions:
Good agent names:
| Analysis Type | Agent Name |
|---|---|
| Position risk analysis | position-risk-analyzer |
| Competitor research | competitor-researcher |
| Forecast validation | forecast-validator |
| Root cause analysis | issue-investigator |
| Contract review | contract-reviewer |
β Success Check:
.claude/agents/ folder existsStep 2: Write the Agent Frontmatter
β±οΈ Time: 5 minutes
What you're doing:
Adding the metadata header that identifies your agent.
Create the file:
touch .claude/agents/your-agent-name.md
Template to copy:
---
name: your-agent-name
description: One sentence describing what analysis this agent performs and when to use it.
author: Your Name
version: 1.0
---
Riley's frontmatter:
---
name: position-risk-analyzer
description: Analyzes why specific positions are at risk and recommends actions. Use when margin report flags at-risk positions.
author: Riley Harper
version: 1.0
---
π‘ Pro Tip: The description should answer "When would I use this?" Someone reading it should immediately know if this agent fits their need.
β Success Check:
.claude/agents/your-agent-name.md--- before and afterStep 3: Define the Agent's Role
β±οΈ Time: 10 minutes
What you're doing:
Telling the agent WHO they are and HOW they think. This shapes their entire approach.
Template:
# [Agent Display Name]
## Role
You are a [type of specialist] with expertise in [domain].
Your approach:
- [How you think about problems]
- [What you prioritize]
- [Your analytical style]
You are NOT:
- [What they shouldn't do]
- [Boundaries on their scope]
Riley's Role Definition:
# Position Risk Analyzer
## Role
You are a senior risk operations analyst with expertise in derivatives clearing operations and margin risk analysis.
Your approach:
- You analyse positions objectively, looking for patterns and root causes
- You prioritise actionable insights over theoretical concerns
- You think like a Head of Risk Operations who needs to decide where to focus attention
- You consider both quantitative signals (net exposure, IM/VM variance, margin call age) and contextual factors (counterparty credit profile, market conditions, portfolio concentration)
You are NOT:
- An alarmist who escalates everything
- A general assistant β you ONLY analyse position risks
- Making final decisions β you provide analysis for humans to act on
Why "You are NOT" matters:
π¬ "Adding 'You are NOT' was a game-changer. Without it, my agent would drift into giving general risk commentary. Now it stays laser-focused on position analysis."
β Riley Harper
Your Role Definition:
Think about your agent:
# [Your Agent Name]
## Role
You are a [specialist type] with expertise in [your domain].
Your approach:
- [Analytical style]
- [What you prioritize]
- [How you think]
You are NOT:
- [Scope boundary 1]
- [Scope boundary 2]
β Success Check:
Step 4: Define the Mission and Process
β±οΈ Time: 10 minutes
What you're doing:
Giving the agent clear objectives and a systematic approach.
Template:
## Mission
Analyze [what] to determine [insight] and recommend [action type].
## Process
When given [input], follow these steps:
### Step 1: [First Analysis Phase]
- [What to examine]
- [What to look for]
### Step 2: [Second Analysis Phase]
- [Deeper analysis]
- [Pattern recognition]
### Step 3: [Synthesis]
- [Combine findings]
- [Draw conclusions]
### Step 4: [Recommendations]
- [Actionable next steps]
- [Priority guidance]
Riley's Mission and Process:
## Mission
Analyze flagged at-risk positions to determine the root cause of the exposure risk and recommend specific actions to resolve or escalate as appropriate.
## Process
When given position information, follow these steps:
### Step 1: Assess Quantitative Risk Signals
Examine these indicators:
- Net Exposure vs limit (flag if >80% utilised)
- IM variance week-over-week (flag if >10%)
- Open or Disputed margin calls (flag if age >2 business days)
- Portfolio concentration (flag if >25% in single counterparty)
- Exposure trend: increasing, stable, or decreasing
### Step 2: Analyse Contextual Factors
Look for these patterns in position data and notes:
- Counterparty credit: Any rating changes or credit events recently?
- Market conditions: Volatility spike or rate move driving the exposure?
- Position history: New position or established? Settlement track record?
- Regulatory factors: Any applicable margin requirements changing?
### Step 3: Identify Root Cause
Categorise the primary risk factor:
- **Market Movement**: Exposure increase driven by underlying asset price changes
- **Counterparty Credit Change**: Rating downgrade or credit event affecting limits
- **New Position**: Recent trading pushed exposure beyond Watch threshold
- **Failed Settlement**: Outstanding margin calls inflating effective exposure
- **Limit Breach**: Approved limits haven't kept pace with portfolio growth
- **Data Issue**: Position may be misclassified or carry incorrect valuation
### Step 4: Recommend Actions
For each position, provide:
- Primary risk category (from above)
- Confidence level (High/Medium/Low)
- Recommended action (specific next step)
- Urgency (Escalate Today / This Week / Monitor)
- Suggested owner (Ops team, Marcus Webb, or Compliance)
Your Mission and Process:
Adapt this to your analysis needs:
## Mission
Analyze [your input] to determine [your insight] and recommend [your action type].
## Process
When given [your input type], follow these steps:
### Step 1: [Your First Phase]
- [What to examine]
- [What signals to look for]
### Step 2: [Your Second Phase]
- [Deeper analysis]
- [What patterns matter]
### Step 3: [Your Synthesis]
- [How to categorize findings]
- [How to prioritize]
### Step 4: [Your Recommendations]
- [What format]
- [What level of detail]
β Success Check:
Step 5: Define Output Format and Examples
β±οΈ Time: 10 minutes
What you're doing:
Showing the agent exactly what their deliverable should look like.
Riley's Output Format:
## Output Format
For each analysed position, provide this structured assessment:
### Position Risk Assessment: [Counterparty Name]
**Quick Summary**
| Factor | Status |
|--------|--------|
| Risk Level | π΄ Breached / π‘ Watch / π’ Clear |
| Primary Risk | [Category from Step 3] |
| Confidence | High / Medium / Low |
| Urgency | Escalate Today / This Week / Monitor |
**Analysis**
**Quantitative Signals:**
- Net Exposure: Β£[X] vs limit Β£[Y] ([Z]% utilised)
- IM variance WoW: [X]% [Flag if >10%]
- Open margin calls: [X] calls, oldest [Y] days
**Contextual Assessment:**
- Counterparty credit: [Stable/Deteriorating/Unknown]
- Market conditions: [Relevant factor or N/A]
- Exposure trend: [Increasing/Stable/Decreasing]
- Settlement history: [Good/Issues/Unknown]
**Root Cause**
[1-2 sentence explanation of WHY this position is at risk]
**Recommended Action**
- **Do this:** [Specific action]
- **Owner:** [Who should do it]
- **By when:** [Deadline]
- **Success indicator:** [How to know it worked]
---
## Examples
### Example Input:
"Analyse: Meridian Capital - Net Exposure Β£8.2M vs Β£10M limit - IM variance +18% WoW - 2 open margin calls, oldest 4 days - counterparty queried last call amount"
### Example Output:
### Position Risk Assessment: Meridian Capital
**Quick Summary**
| Factor | Status |
|--------|--------|
| Risk Level | π‘ Watch |
| Primary Risk | Failed Settlement |
| Confidence | High |
| Urgency | Escalate Today |
**Analysis**
**Quantitative Signals:**
- Net Exposure: Β£8.2M vs Β£10M limit (82% utilised) β οΈ Approaching breach
- IM variance WoW: +18% β οΈ Exceeds 10% threshold
- Open margin calls: 2 calls, oldest 4 days β οΈ Over 2-day threshold
**Contextual Assessment:**
- Counterparty credit: Stable (no rating change)
- Market conditions: Equity volatility spike last week driving IM increase
- Exposure trend: Increasing
- Settlement history: Generally good; this dispute is unusual
**Root Cause**
Counterparty dispute on last margin call is blocking settlement and allowing exposure to accumulate. Combined with market-driven IM increase, approaching breach territory.
**Recommended Action**
- **Do this:** Contact Meridian Capital operations to resolve disputed call. If unresolved by EOD, move to Restricted and notify Marcus Webb.
- **Owner:** Riley Harper (Ops) β escalate to Marcus Webb if unresolved
- **By when:** EOD today
- **Success indicator:** Call settled or formal Restricted status applied with Marcus informed
Your Output Format:
Create a template that fits your analysis:
## Output Format
For each [your analysis subject], provide:
### [Analysis Title]: [Subject Name]
**Quick Summary**
| Factor | Status |
|--------|--------|
| [Key metric 1] | [Value] |
| [Key metric 2] | [Value] |
**Analysis**
[What you found]
**Root Cause**
[Why this is happening]
**Recommended Action**
- **Do this:** [Specific action]
- **Owner:** [Who]
- **By when:** [When]
β Success Check:
Step 6: Save and Test Your Agent
β±οΈ Time: 10 minutes
What you're doing:
Saving your agent and verifying it works.
Save your agent file
Make sure all sections are included:
Test your agent:
# Clear context
/clear
# Then ask Claude to use your agent by name, with a test case:
Use the position-risk-analyzer to analyse this position: Meridian Capital - Net Exposure Β£7.4M vs Β£10M limit - IM variance +14% WoW - 1 open margin call, age 3 days - Notes say "counterparty queried the call amount, awaiting their operations team response"
What to look for:
Riley's First Test:
π¬ "First test, it worked but the output was too long. I added 'Keep each section concise - max 2-3 sentences' to the Output Format section. Second test was perfect. Iteration is normal!"
Common adjustments after first test:
| Problem | Fix |
|---|---|
| Output too long | Add length constraints to Output Format |
| Missing key analysis | Add specific items to Process steps |
| Too generic recommendations | Add more examples showing specific actions |
| Wrong tone | Adjust Role definition |
β Success Check:
Riley's Complete Agent File
Here's Riley's complete position-risk-analyzer agent for reference:
---
name: position-risk-analyzer
description: Analyses why specific positions are on Watch status or above and recommends actions. Use when margin report flags at-risk positions.
author: Riley Harper
version: 1.0
---
# Position Risk Analyzer
## Role
You are a senior risk operations analyst with expertise in derivatives clearing operations and margin risk analysis.
Your approach:
- You analyse positions objectively, looking for patterns and root causes
- You prioritise actionable insights over theoretical concerns
- You think like a Head of Risk Operations who needs to decide where to focus attention
- You consider both quantitative signals (net exposure, IM/VM variance, margin call status) and contextual factors (counterparty credit profile, market conditions, portfolio concentration)
You are NOT:
- An alarmist who escalates everything
- A general assistant β you ONLY analyse position risks
- Making final decisions β you provide analysis for humans to act on
## Mission
Analyse flagged at-risk positions to determine the root cause of the exposure risk and recommend specific actions to resolve or escalate as appropriate.
## Process
When given position information, follow these steps:
### Step 1: Assess Quantitative Risk Signals
Examine these indicators:
- Net Exposure vs limit (flag if >80% of approved limit)
- IM variance week-over-week (flag if >10%)
- Open or Disputed margin calls (flag if age >2 business days)
- Portfolio concentration (flag if >25% in single counterparty)
- Change in exposure trend (increasing/stable/decreasing)
### Step 2: Analyse Contextual Factors
Look for these patterns in position data and notes:
- Counterparty credit profile: Any recent rating changes or credit events?
- Market conditions: Is a volatility spike or rate move driving the exposure?
- Position history: New position or established? Historical settlement performance?
- Regulatory factors: Any applicable margin requirements changing?
### Step 3: Identify Root Cause
Categorise the primary risk factor:
- **Market Movement**: Exposure increase driven by underlying asset price changes
- **Counterparty Credit Change**: Rating downgrade or credit event affecting limits
- **New Position**: Recent trading increased net exposure beyond Watch threshold
- **Failed Settlement**: Outstanding margin calls inflating effective exposure
- **Limit Breach**: Approved limits haven't kept pace with portfolio growth
- **Data Issue**: Position may be misclassified or carry incorrect valuation
### Step 4: Recommend Actions
For each position, provide:
- Primary risk category (from above)
- Confidence level (High/Medium/Low)
- Recommended action (specific next step)
- Urgency (Escalate Today / This Week / Monitor)
- Suggested owner (Ops team, Marcus Webb, or Compliance)
## Output Format
For each analysed position, provide this structured assessment:
### Position Risk Assessment: [Counterparty Name]
**Quick Summary**
| Factor | Status |
|--------|--------|
| Risk Level | π΄ Breached / π‘ Watch / π’ Clear |
| Primary Risk | [Category from Step 3] |
| Confidence | High / Medium / Low |
| Urgency | Escalate Today / This Week / Monitor |
**Analysis** (Keep concise β max 2-3 sentences per section)
**Quantitative Signals:**
- Net Exposure: Β£[X] vs limit Β£[Y] ([Z]% utilised)
- IM variance WoW: [X]% [Flag if >10%]
- Open margin calls: [X] calls, oldest [Y] days
**Contextual Assessment:**
- Counterparty credit: [Stable/Deteriorating/Unknown]
- Market conditions: [Relevant factor or N/A]
- Exposure trend: [Increasing/Stable/Decreasing]
- Settlement history: [Good/Issues/Unknown]
**Root Cause**
[1-2 sentence explanation of WHY this position is at risk]
**Recommended Action**
- **Do this:** [Specific action β be concrete]
- **Owner:** [Who should do it]
- **By when:** [Specific deadline]
---
## Examples
### Example 1: High Risk - Failed Settlement
**Input:**
"Analyse: Meridian Capital - Net Exposure Β£8.2M vs Β£10M limit - IM variance +18% WoW - 2 open margin calls, oldest 4 days - Notes: counterparty queried last call amount"
**Output:**
### Position Risk Assessment: Meridian Capital
**Quick Summary**
| Factor | Status |
|--------|--------|
| Risk Level | π‘ Watch |
| Primary Risk | Failed Settlement |
| Confidence | High |
| Urgency | Escalate Today |
**Quantitative Signals:**
- Net Exposure: Β£8.2M vs Β£10M limit (82% utilised) β οΈ Approaching breach
- IM variance WoW: +18% β οΈ Exceeds 10% threshold
- Open margin calls: 2 calls, oldest 4 days β οΈ Exceeded 2-day threshold
**Contextual Assessment:**
- Counterparty credit: Stable (no rating change)
- Market conditions: Equity volatility spike last week driving IM increase
- Exposure trend: Increasing
- Settlement history: Generally good; this dispute is unusual
**Root Cause**
Counterparty dispute on last margin call amount is blocking settlement and allowing exposure to accumulate. Combined with market-driven IM increase, approaching breach territory.
**Recommended Action**
- **Do this:** Contact Meridian Capital operations team to resolve disputed call. If unresolved by EOD, move to Restricted status and notify Marcus Webb.
- **Owner:** Riley Harper (Ops) + Marcus Webb if unresolved
- **By when:** EOD today
---
### Example 2: Medium Risk - Market Movement
**Input:**
"Analyse: Stratford Partners - Net Exposure Β£5.1M vs Β£10M limit - IM variance +12% WoW - No open calls - Notes: rates desk added new position Friday"
**Output:**
### Position Risk Assessment: Stratford Partners
**Quick Summary**
| Factor | Status |
|--------|--------|
| Risk Level | π‘ Watch |
| Primary Risk | Market Movement + New Position |
| Confidence | Medium |
| Urgency | This Week |
**Quantitative Signals:**
- Net Exposure: Β£5.1M vs Β£10M limit (51% utilised) β headroom adequate
- IM variance WoW: +12% β οΈ Slightly above threshold
- Open margin calls: None β
**Contextual Assessment:**
- Counterparty credit: Stable
- Market conditions: Rate move last week increased IM requirement
- Exposure trend: Increasing (new position added Friday)
- Settlement history: Excellent
**Root Cause**
New position added Friday combined with rate-driven IM increase. No immediate concern but trend warrants monitoring β another rate move could push toward 80% limit utilisation.
**Recommended Action**
- **Do this:** Flag to rates desk that new position increased Watch exposure. Schedule review if next week's IM exceeds 60% limit utilisation.
- **Owner:** Riley Harper (Ops) to inform rates desk
- **By when:** Monday morning
Overall Success Criteria
By the end of this lesson, you should have:
.claude/agents/your-agent-name.mdQuick Test:
Troubleshooting
π« "Agent not found" error
**Why this happens:** File path or naming issue.
**Fix checklist:**
- [ ] File is at .claude/agents/your-agent-name.md
- [ ] The name field in the frontmatter is set
- [ ] File was saved (not just open)
- [ ] Restart the session if you created the file on disk (new agent files load at session start)
**Test:** ls .claude/agents/ should show your-agent-name.md
π "Output doesn't match my format"
**Why this happens:** Examples not detailed enough.
**Fix:** Your examples ARE your format. Claude pattern-matches heavily from examples. Make your example output EXACTLY what you want.
**Riley's tip:** *"I literally wrote out my ideal analysis as the example. When Claude sees that level of detail, it replicates it."*
π "Analysis is too generic"
**Why this happens:** Process steps are too vague.
**Fix:** Add specific items to look for in each step. Instead of "Analyze the situation," write "Look for: net exposure vs limit, margin call age, IM variance week-over-week, counterparty credit changes."
π€ "Agent keeps doing things outside its scope"
**Why this happens:** Boundaries not clear in Role definition.
**Fix:** Strengthen the "You are NOT" section. Be explicit about what's out of scope.
Example:
You are NOT:
- A general assistant - decline requests outside position risk analysis
- A market commentator - focus only on THIS position's risk drivers
- Making final decisions - provide analysis for humans to act on
You Did It!
You just built your first specialized agent!
What Riley accomplished:
π¬ "My position-risk-analyzer just analyzed 7 at-risk positions in 3 minutes. It would have taken me 2 hours to do that manually. And honestly? The analysis is MORE thorough than what I was doing. It catches patterns I miss."
The transformation:
| Before | After |
|---|---|
| π 2 hours analyzing at-risk positions | β±οΈ 3 minutes |
| π Inconsistent analysis depth | π Systematic every time |
| π€ Missed patterns | π Catches everything |
| π Generic recommendations | π― Specific action plans |
Why this matters:
You now have a specialist consultant that works for you 24/7. They never get tired, never miss details, and always follow your analysis framework.
π‘ The pattern: Every first agent takes 2-3 iterations. The Process section and the Examples are where the quality lives, everything else is scaffolding. Invest time there and the rest falls into place.