Samsung’dan araç tutmasına karşı özel uygulama: “Hearapy”

Samsung

Samsung'dan araç tutmasına karşı özel uygulama: "Hearapy"“Her 10 yolcudan 3’ünde görülen araç tutması (hareket hastalığı), seyahatleri kabusa çevirebiliyor.” diyen Samsung, buna çözüm olarak “Hearapy” isimli yeni bir Android uygulaması yayımladı. Ücretsiz olarak yayımlanan uygulama, spesifik olarak Galaxy Buds 4 Pro için öne çıkarılıyor; ancak belirli teknik detayları karşılayan tüm kulaklıklarla kullanılabiliyor. Şirketin açıklamasına göre hazırlanan uygulama 85 dB ses yüksekliğiyle 100 Hz frekansta sabit bir ses çalıyor ve yolculuk öncesinde 60 saniye boyunca bu sesin dinlenmesi, denge sistemini uyararak kişilerin yol boyunca kendilerini iyi hissetmesini sağlıyor. “Araştırmalar, sadece 60 saniyelik saf 100 Hz sinüs dalgasının araç tutmasını ciddi oranda azalttığını gösteriyor. Etkisi iki saate kadar süren bu yöntem, iç kulaktaki denge organını doğrudan uyararak vücudunuzun çelişen duyusal girdilerini ilaçsız bir şekilde dengelemesine yardımcı oluyor.” açıklamasının yapıldığı faydalı uygulama, direkt olarak buradan (Play Store) elde edilebiliyor.

Samsung’dan araç tutmasına karşı özel uygulama: “Hearapy” yazısı ilk olarak Teknoloji haberleri – LOG üzerinde yayınlandı.

Master Coding Interviews : Part 2 ( Two Pointers Pattern )

Two Sum II: Input Array Is Sorted

If you read Part 1 of this series, you already know how a single pattern can transform a slow, brute-force solution into an elegant, optimized one. Today we’re going to do the same thing — but with a different tool in our belt: the Two Pointers pattern.

This one is everywhere in coding interviews. Once you recognize it, you’ll start seeing it in problems you might have struggled with before.

What is the Two Pointers Pattern?

The idea is simple: instead of using one index to iterate through your data structure, you use two. These two pointers move through the array (or string) according to specific conditions, and together they help you find the answer without needing nested loops.

There are two main variants you’ll encounter:

  • Opposite-direction pointers : One pointer starts at the beginning, the other at the end. They move toward each other until they meet.
  • Same-direction pointers (fast & slow) : Both pointers start at the same end, but move at different speeds or under different conditions.

Let’s jump straight into a problem to see the first variant in action.

Problem 1 — Two Sum II: Input Array Is Sorted

Two Sum II: Input Array Is Sorted

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return the indices of the two numbers as an integer array [index1, index2] of length 2.

The brute-force approach is fairly intuitive: try every possible pair and check whether it adds up to the target.

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        for i in range(len(numbers)):
            for j in range(i + 1, len(numbers)):
                if numbers[i] + numbers[j] == target:
                    return [i + 1, j + 1]  # 1-indexed result
        return []

This works — but just like in Part 1, it hides a performance problem we can’t ignore:

  • Time complexity : O(n²) : For an array of 30,000 elements, this is potentially 900 million comparisons.
  • Time Limit Exceeded : For large inputs on LeetCode, this solution will almost certainly hit the TLE wall.

  • In a real production context, a quadratic loop like this over large datasets is a performance bottleneck waiting to happen.

Optimization through the Two Pointers Pattern

Here’s the key insight we’re missing in the brute-force: the array is already sorted. That’s a hint the problem is giving us for free, and the Two Pointers pattern is exactly how we take advantage of it.

We place one pointer at the very beginning of the array (left) and one at the very end (right). Then we look at their sum:

  • If the sum equals the target → we’re done.
  • If the sum is too large → we need a smaller number, so we move right one step to the left.
  • If the sum is too small → we need a larger number, so we move left one step to the right.

Each iteration eliminates a candidate, and since both pointers are converging toward the center, we’ll find the answer — or confirm it doesn’t exist — in a single pass.

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        left = 0                    # Left pointer starts at the beginning
        right = len(numbers) - 1   # Right pointer starts at the end

        while left < right:
            current_sum = numbers[left] + numbers[right]

            if current_sum == target:
                # Found the pair — return 1-indexed positions
                return [left + 1, right + 1]

            elif current_sum > target:
                # Sum is too large: move right pointer inward to get a smaller value
                right -= 1

            else:
                # Sum is too small: move left pointer inward to get a larger value
                left += 1

        return []  # No solution found (problem guarantees one exists, but good practice)

This brings us down to O(n) time complexity and O(1) space complexity — a dramatic improvement over the brute-force approach, and it passes LeetCode with no issues.

Variant 2 — Same-Direction Pointers

The second variant doesn’t converge from opposite ends. Instead, both pointers start from the same side and move in the same direction, but at different speeds or under different conditions. This is perfect for problems where you need to restructure an array in-place or detect a specific pattern as you scan forward.

Let’s look at a classic example.

Problem 2 — Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements k.

The naïve instinct here might be to use a set to collect unique values and rebuild the array — but the problem explicitly requires an in-place solution using O(1) extra memory. A set would cost us O(n) space, which defeats the purpose.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        seen = set()
        result = []

        for num in nums:
            if num not in seen:
                seen.add(num)
                result.append(num)

        # This doesn't satisfy the in-place constraint
        for i in range(len(result)):
            nums[i] = result[i]

        return len(result)

Beyond the space constraint violation, this approach creates auxiliary data structures we don’t need. The Two Pointers pattern gives us a cleaner — and compliant — solution.

Optimization: Same-Direction Two Pointers

Here’s the idea: we use a slow pointer to track the position where the next unique element should be written, and a fast pointer to scan ahead through the array looking for new unique values. Whenever fast finds a value different from what slow is pointing at, we advance slow and write that new value there.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # 'slow' marks the boundary of our unique-elements section
        slow = 0

        # 'fast' scans ahead to discover new unique elements
        for fast in range(1, len(nums)):

            # When fast finds a value different from slow's position,
            # a new unique element has been discovered
            if nums[fast] != nums[slow]:
                slow += 1                  # Expand the unique section
                nums[slow] = nums[fast]    # Write the new unique value in place

        # slow is now the index of the last unique element
        # so the count of unique elements is slow + 1
        return slow + 1

Time complexity : O(n) — fast does a single pass through the array.

Space complexity : O(1) — everything is done in-place, no extra data structures.

The elegance here is that the two pointers work as a team: fast does the exploration, slow does the writing. They never interfere with each other because slow can only be at or behind fast.

When to use this pattern

  • When dealing with sorted arrays or strings (a big hint for opposite-direction pointers)
  • When the problem asks you to find a pair (or triplet) of elements that satisfy a condition
  • When you need to restructure or deduplicate an array in-place with O(1) space
  • When the brute-force solution involves nested loops over the same linear data structure — that’s almost always a signal that two pointers can collapse it to O(n)

What’s next ? Practice

Head over to LeetCode and try the Two Pointers problem list — there are over 200 problems tagged with this pattern. Start with the easy ones to build your instinct, then move into medium difficulty.

A few good ones to try next:

  • Container With Most Water (Medium) — opposite-direction pointers
  • 3Sum (Medium) — two pointers inside an outer loop
  • Linked List Cycle (Easy) — fast & slow pointers on a linked list

PS: As with the Sliding Window pattern, Two Pointers isn’t always the only valid approach. It’s a powerful tool when certain conditions are met — sorted data, in-place constraints, pair/subset problems — but always think about whether the pattern genuinely fits before reaching for it.

See you in the next article for another coding pattern !

Ways to Learn Vim in 2026: A Complete Beginner’s Guide

If you had asked someone five years ago whether learning Vim was necessary, they might have called it a niche flex for greybeards. But in 2026, the landscape of software development has shifted dramatically. The terminal is back, and it brought AI with it.

Tools like Claude Code, Cursor’s terminal, Copilot CLI, and Warp are pushing developers out of heavy GUIs and back into the command line. But there’s a catch: to use terminal-first AI tools efficiently, you need to know how to navigate and edit text without reaching for your mouse.

Vim keybindings are now everywhere – from VS Code and JetBrains to Obsidian and browser extensions. Knowing Vim is no longer just about looking cool; it’s becoming a practical necessity for the AI-augmented workflow. Here is a complete beginner’s guide to why and how to learn Vim today.

Why Even Learn Vim? (The Honest Case)

The learning curve is notorious. So why put yourself through it?

  • Speed & Efficiency: Vim allows you to edit at the speed of thought. Every time you move your hand from the keyboard to the mouse to highlight a word, you lose context. Vim keeps you in the flow.

  • The Grammar of Composability: Vim isn’t just a list of shortcuts to memorize. It’s a language. It uses a “verb + noun” grammar (operator + motion). Once you know that d is delete, c is change, w is word, and i" is inside quotes, you instantly know how to diw (delete inside word) or ci" (change inside quotes). A small set of building blocks creates hundreds of commands.

  • Ubiquity: vi and vim are pre-installed on virtually every server, Linux distribution, and Docker container on the planet. When you SSH into a broken server, your favorite electron-based editor won’t be there to save you.

  • A One-Time Investment: JavaScript frameworks change every three years. Vim has been around for decades. The muscle memory you build today will pay dividends until the day you retire.

  • The Career Signal: Let’s be honest – navigating code effortlessly in the terminal signals depth, craft, and a deep understanding of your tools to peers and interviewers.

7 Ways to Learn Vim: Ranked and Reviewed

There is no single “correct” way to learn Vim. The best approach usually involves combining a few methods. Here is an honest breakdown of your options.

1. The Built-in Classic: vimtutor

Open your terminal and type vimtutor. It’s a built-in, interactive text file that teaches you the absolute basics.

  • Pros: Free, pre-installed everywhere, gets you moving in 30 minutes.

  • Cons: It’s dry. There’s no visual feedback, no scoring, and it leaves you with the classic “I finished vimtutor, now what?” problem.

  • Best for: Day 1. Getting your hands on hjkl and learning how to save and quit (:wq).

2. “Cold Turkey” (Editor Extensions)

Installing a Vim extension in VS Code or IntelliJ and forcing yourself to use it for your daily work.

  • Pros: Builds muscle memory incredibly fast because you have real work to do.

  • Cons: Extremely frustrating without a foundation. Your productivity will tank for the first week, and most people give up after an hour.

  • Best for: Developers who already know the basic motions and want to force the transition.

3. Mobile Companion Apps (e.g., VimKata)

Mobile apps allow you to practice Vim motions when you are away from your keyboard – during a commute or a coffee break. Apps like VimKata provide animated demos of what commands do before you practice them on real code snippets.

  • Pros: Visual feedback, gamified scoring based on efficiency (not just typing the “right” answer), bite-sized learning. It teaches the composable grammar as a system.

  • Cons: It’s a companion tool. You still need to transfer that knowledge to a physical keyboard eventually.

  • Best for: Beginners who want structured, visual learning to bridge the gap between vimtutor and daily coding.

4. YouTube Tutorials & Video Courses

Watching creators like ThePrimeagen or DistroTube navigate code like wizards.

  • Pros: Highly motivating. Shows you the true potential and ceiling of Vim mastery.

  • Cons: Passive learning. Watching someone type dt) (delete till parenthesis) doesn’t build your muscle memory.

  • Best for: Inspiration and discovering advanced workflows.

5. Interactive Web Games (Vim Adventures)

Browser-based games where you move a character using Vim keys.

  • Pros: A fun, non-threatening entry point, especially for non-developers.

  • Cons: They usually only cover basic motions, lack real code context, and development on them has mostly stagnated.

  • Best for: The absolute first taste of Vim mechanics.

6. Books (Practical Vim)

Deep dives into the philosophy and advanced mechanics of the editor.

  • Pros: Comprehensive and incredibly eye-opening for intermediate users.

  • Cons: Too dense for Day 1 beginners who just need to figure out how to enter Insert mode without panicking.

  • Best for: Leveling up after you have survived your first month.

7. Cheat Sheets

A PDF or desktop wallpaper with 100+ commands.

  • Pros: Great quick reference.

  • Cons: Terrible as a primary learning method. Memorizing a list without context won’t stick.

  • Best for: Supplementing your primary learning method.

Comparing the Methods

Method Real Code Context Visual Feedback Structured Path Best For
vimtutor No (Text blocks) No Yes (Basic) Absolute Day 1
Cold Turkey Yes (Your code) Yes No Ripping the band-aid off
Companion Apps Yes (Snippets) Yes (Animations) Yes Daily micro-habits
Video Courses Yes Yes Variable Inspiration & Theory

The Beginner’s Practical Roadmap

Don’t try to learn everything at once. Follow this timeline:

  1. Day 1: Open your terminal and run vimtutor. Get comfortable with hjkl, i (insert), Esc, and :wq.

  2. Week 1: Focus on micro-habits. Use a companion app like VimKata for 10-15 minutes a day during downtime to visually understand how operators and motions combine.

  3. Week 2: Enable the Vim extension in your primary editor (VS Code, JetBrains). Keep a cheat sheet on your second monitor. Accept that you will be slower for a few days.

  4. Weeks 3-4: Stop moving character by character. Focus entirely on the grammar: combining d, c, and y with motions like w (word), $ (end of line), and % (matching bracket).

  5. Month 2+: Start customizing. Build your .vimrc or init.lua incrementally. When you catch yourself reaching for the mouse, pause and google “how to do X in Vim”.

The AI-Era Angle: Why Now?

If you’re using tools like Claude Code, you are reading, navigating, and editing code directly within a terminal context. AI agents are incredibly fast at generating edits, but as the human in the loop, you still need to review, jump between files, and apply tweaks efficiently.

The modern power-user setup that AI tools assume you have is a terminal multiplexer (like tmux) paired with a terminal-based editor (Neovim). GUI-heavy workflows are slowly giving way to Terminal + AI workflows. Learning Vim in 2026 isn’t about rejecting modern technology; it’s about mastering the interface that AI is naturally converging on.

Just Start

Don’t overthink finding the “perfect” way to learn. 10 minutes of practice a day will always beat a 4-hour weekend cram session that you never repeat.

Your next step is simple: open your terminal and type vimtutor, or download VimKata to start practicing visually on your phone. Just take the first step. Your future self will thank you.

I spent 8 weeks building a Nash Equilibrium calculator from scratch in Python

Hey everyone,

I am someone who has been wanting to apply computer science into economics and mathematics and hence I decided to build a Nash Equilibrium calculator of sorts using Python and other libraries in Python like numpy and scipy.optimize.

The solver calculates all pure and mixed nash equilibria using the support enumeration algorithm. It also uses linear programming, which I did through the HiGHS solver, for the iterated elimination of strictly dominated strategies. I also built a small sub feature where the tool calculates game values for zero sum games using the Von Neumann Minimax theorem by identifying the Pareto optimal outcomes and hence calculating the social welfare loss. To make it visually easy to read, I used the rich library to build a terminal UI that color-codes the matrices.

This project took me almost 8 weeks to complete and I had to force myself to not use AI at all and hence the code might be a bit wonky.

Nonetheless, would be great if y’all could check it out and as always, open to any and all comments for improvement regarding the code or the math.

Here is the repo on GitHub, please go check it out: Github Link

Cómo crear un sistema de pago por minuto en PHP (caso real aplicado a streaming) con wordpress

Uno de los modelos de monetización más utilizados en plataformas de streaming es el pago por minuto.

En este artículo te voy a mostrar cómo implementar este sistema usando PHP dentro de WordPress, basado en un caso real donde se desarrolló una plataforma de transmisión en vivo.

¿Qué es un sistema de pago por minuto?

Es un modelo donde:

El usuario paga mientras consume el contenido
El saldo se descuenta automáticamente cada cierto tiempo
El creador recibe una parte del dinero

Este sistema es común en plataformas de:

Streaming en vivo
Consultorías online
Contenido premium
⚙️ Lógica básica del sistema

La implementación se basa en 3 elementos clave:

Saldo del usuario
Costo por minuto
Intervalo de descuento automático

Almacenamiento del saldo

En WordPress, el saldo se puede guardar usando user_meta:

add_user_meta($user_id, ‘saldo_disponible’, 0, true);

Esto permite manejar un sistema simple sin necesidad de tablas complejas.

Descuento automático por minuto

Cada minuto se ejecuta una función que descuenta saldo:

function descontar_saldo($user_id) {
$saldo = floatval(get_user_meta($user_id, ‘saldo_disponible’, true));

if ($saldo <= 0) return 0;

$nuevo = $saldo - 3000;
update_user_meta($user_id, 'saldo_disponible', $nuevo);

return $nuevo;

}

Ejecución en tiempo real (AJAX)

Para ejecutar esto sin recargar la página:

setInterval(() => {
fetch(‘/wp-admin/admin-ajax.php’, {
method: ‘POST’,
body: new URLSearchParams({
action: ‘descuento_minuto’
})
});
}, 60000);

Esto permite descontar saldo automáticamente mientras el usuario está conectado.

Distribución de ganancias

En el caso real:

Usuario paga: 3000 COP por minuto
Creador recibe: 1500 COP (50%)
function sumar_ganancia_creador($user_id) {
$saldo = get_user_meta($user_id, ‘saldo_disponible’, true);
$nuevo = $saldo + 1500;
update_user_meta($user_id, ‘saldo_disponible’, $nuevo);
}

Validación de saldo antes de iniciar

Antes de permitir el acceso:

function tiene_saldo($user_id) {
$saldo = get_user_meta($user_id, ‘saldo_disponible’, true);
return $saldo >= 3000;
}

Esto evita accesos sin pago.

Aplicación real

Este tipo de sistema ya se utiliza en plataformas donde los usuarios acceden a contenido en tiempo real con pagos directos, combinando streaming, interacción y monetización.

Consideraciones importantes

Validar saldo constantemente
Evitar que el usuario siga conectado sin crédito
Sincronizar frontend y backend
Controlar errores en AJAX

Implementar un sistema de pago por minuto en PHP es más sencillo de lo que parece si se estructura correctamente.

Con herramientas nativas de WordPress y un poco de JavaScript, es posible crear modelos de monetización en tiempo real sin depender de servicios externos.

Chapter 4. How to Use — Sub Agents

4.1 What Is a Sub Agent?

A Sub Agent is a specialized AI assistant dedicated to handling specific tasks within a Claude Code session.

If the main Claude Code is the “general manager,” Sub Agents are “team members,” each with their own area of expertise.
Each Sub Agent operates with its own independent context window, dedicated system prompt, and restricted tool access.

┌──────────────────────────────────────────────┐
│  Main Claude Code Session (General Manager)  │
│                                              │
│  "Review this code"                          │
│      ↓ delegate                              │
│  ┌──────────────────────────────────┐        │
│  │  Sub Agent: code-reviewer        │        │
│  │  • Independent context window    │        │
│  │  • Read-only tools allowed       │        │
│  │  • Code review system prompt     │        │
│  └──────────────┬───────────────────┘        │
│                 ↓ return result              │
│  "Review complete: 3 improvements found"     │
└──────────────────────────────────────────────┘

4.2 Purpose and Role

Why Use Sub Agents?

Purpose Description
Context preservation Exploration and analysis results do not pollute the main conversation. Sub Agents return only a summary, keeping the main context clean
Specialization Role-specific system prompts for tasks like code review, test writing, and security analysis improve accuracy
Tool restriction Apply the principle of least privilege — e.g., grant only Read to review agents, and Write/Edit to implementation agents
Reusability A Sub Agent created once can be used across all projects (user scope)

Built-in Sub Agents

Claude Code includes built-in Sub Agents that are used automatically.

Name Tools Role
Explore Read-only Search and navigate the codebase. No file modifications
Plan Read-only Analyze the codebase before implementation in Plan Mode
General-purpose All tools Complex multi-step tasks (exploration + modification)
Bash Terminal Execute commands in a separate context

These built-in agents are delegated to automatically by Claude.
The user does not need to invoke them directly — they are selected automatically based on the nature of the task.

4.3 Setup and Verification

Method 1: /agents Command (Recommended)

> /agents

From the interactive menu, you can:

  1. Select Create new agent
  2. Choose Personal (all projects) or Project (current project only)
  3. Select Generate with Claude → enter a description of the role
  4. Choose tool access scope (Read-only, all tools, etc.)
  5. Select a model (Sonnet, Opus, Haiku)
  6. Choose a background color → save

Example: Creating a Code Review Agent

> /agents
→ Create new agent
→ Personal
→ Generate with Claude
→ "An agent that analyzes code and suggests improvements from the perspective of readability, performance, and best practices"
→ Select Read-only tools
→ Sonnet
→ Save

Method 2: Writing a Markdown File Directly

# Personal use (all projects)
mkdir -p ~/.claude/agents
nano ~/.claude/agents/code-reviewer.md

# Project use (current project only)
mkdir -p .claude/agents
nano .claude/agents/code-reviewer.md

How to Verify

# List agents from CLI (outside a session)
claude agents

# List agents from within a session
> /agents

How to Invoke

# Automatic delegation — Claude judges automatically based on the description
> Analyze the code quality of this project

# Explicit invocation — specify the agent by name
> Use the code-reviewer agent to review the src/api/ folder

4.4 Sub Agent File Structure

A Sub Agent is composed of a YAML front matter + Markdown body.

File Example: .claude/agents/code-reviewer.md

---
name: code-reviewer
description: Analyzes code quality and suggests improvements from the perspectives of readability, performance, and security. Used when code review or quality analysis is requested.
tools: Read, Grep, Glob
model: sonnet
---

# Code Reviewer Agent

## Role
You are a senior software engineer dedicated to performing code reviews.

## Review Criteria
- Readability: variable names, function structure, comments
- Performance: unnecessary iteration, potential memory leaks
- Security: SQL injection, XSS, hardcoded secrets
- Best practices: adherence to project conventions

## Output Format
For each issue:
1. File path and line number
2. Current code
3. Description of the problem
4. Suggested improved code

YAML Front Matter Fields

Field Required Description
name ✅ Agent identifier (alphanumeric, hyphens allowed)
description ✅ Explains when to use this agent. Claude reads this description to decide whether to delegate automatically
tools ❌ List of allowed tools. If omitted, all tools from the main session are inherited
model ❌ Model to use (sonnet, opus, haiku). Default: the main session model

Tool Restriction Examples

# Read-only (for review and analysis)
tools: Read, Grep, Glob

# Code modification allowed (for implementation)
tools: Read, Write, Edit, Bash, Grep, Glob

# Inherit all tools (omit the field entirely)
# Do not include the tools field at all

Scope by Storage Location

~/.claude/agents/             ← Personal: available across all projects
.claude/agents/               ← Project: available only in this project
                                 (commit to Git to share with the team)

If a Sub Agent with the same name exists in both locations, the project-level agent takes precedence.

Full File Structure Example

my-project/
├── .claude/
│   ├── agents/                    ← Project Sub Agents
│   │   ├── code-reviewer.md
│   │   ├── test-writer.md
│   │   └── security-auditor.md
│   ├── settings.json              ← Project settings (hooks, permissions)
│   └── commands/                  ← Slash commands
├── CLAUDE.md                      ← Project memory
└── .mcp.json                      ← MCP server config (shared with team)

~/.claude/
├── agents/                        ← Personal Sub Agents (all projects)
│   └── general-assistant.md
├── CLAUDE.md                      ← Global memory (personal)
└── settings.json                  ← Personal global settings

4.5 Sub Agent vs MCP — Key Differences

Category Sub Agent MCP Server
Identity A specialized Claude instance A connection to an external tool or service
How it works Claude performs tasks in an independent context An external process provides tool functionality
Context Its own context window (separate from the main session) Shares and consumes the main context window
Config format Markdown file (YAML + prompt) JSON config (command, args, env)
Storage location .claude/agents/ .claude.json or .mcp.json
How it is invoked Claude delegates automatically or by name Claude calls it as a tool
What it can do AI reasoning tasks: code analysis, review, implementation, test writing, etc. External system integration: DB queries, GitHub PRs, browser automation, etc.
Cost Consumes separate tokens (independent context) Consumes context proportional to tool descriptions
Relationship Can use MCP tools Operates independently of Sub Agents

When to Use Which?

"Automatically create a GitHub PR"              → MCP (github server)
"Review this code"                              → Sub Agent (code-reviewer)
"Query user data from the DB"                   → MCP (postgresql server)
"Write test code"                               → Sub Agent (test-writer)
"Find a function by symbol"                     → MCP (serena server)
"Analyze security vulnerabilities"              → Sub Agent (security-auditor)

Key distinction: MCP is a tool for connecting to external systems; Sub Agents are AI instances that perform work in specialized roles.
The two are not substitutes — they are meant to be combined.
Example: a security-auditor Sub Agent uses the Serena MCP’s find_symbol tool to trace vulnerable functions.

4.6 Quick Reference

# ── Sub Agent Management ─────────────────────────────
> /agents                              # Create, view, edit, delete (in session)
claude agents                          # List agents (CLI)

# ── File Locations ───────────────────────────────────
~/.claude/agents/                      # Personal (all projects)
.claude/agents/                        # Project (team-shareable)

# ── Invocation ───────────────────────────────────────
> Analyze using the code-reviewer agent     # Explicit invocation
> Review this code                          # Automatic delegation (description matching)

# ── File Format ──────────────────────────────────────
# .claude/agents/my-agent.md
---
name: my-agent
description: Describe when to use this agent
tools: Read, Grep, Glob            # Omit to inherit all tools
model: sonnet                      # sonnet / opus / haiku
---
System prompt content (Markdown)

Reference: https://code.claude.com/docs/en/sub-agents