惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cisco Talos Blog
Cisco Talos Blog
T
Threat Research - Cisco Blogs
P
Privacy International News Feed
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
Scott Helme
Scott Helme
人人都是产品经理
人人都是产品经理
G
GRAHAM CLULEY
O
OpenAI News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
PCI Perspectives
PCI Perspectives
GbyAI
GbyAI
宝玉的分享
宝玉的分享
Y
Y Combinator Blog
T
Troy Hunt's Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
腾讯CDC
C
Check Point Blog
Spread Privacy
Spread Privacy
L
LINUX DO - 最新话题
Recent Announcements
Recent Announcements
大猫的无限游戏
大猫的无限游戏
P
Palo Alto Networks Blog
Hacker News: Ask HN
Hacker News: Ask HN
M
MIT News - Artificial intelligence
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Hacker News
The Hacker News
H
Hacker News: Front Page
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
T
Tor Project blog
Martin Fowler
Martin Fowler
博客园 - 叶小钗
罗磊的独立博客
C
Cyber Attacks, Cyber Crime and Cyber Security
H
Heimdal Security Blog
V
Vulnerabilities – Threatpost
Simon Willison's Weblog
Simon Willison's Weblog
Latest news
Latest news
WordPress大学
WordPress大学
G
Google Developers Blog
N
Netflix TechBlog - Medium
S
Security Affairs
S
Secure Thoughts
Know Your Adversary
Know Your Adversary

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building an AI Coding Agent from Scratch with Claude Agent SDK
Alex Rogov · 2026-05-01 · via DEV Community

Alex Rogov

Building an AI Coding Agent from Scratch with Claude Agent SDK

You've been using Claude as a chatbot — paste code, get a reply, paste again. That works. But there's a different mode entirely: give Claude a set of tools and a goal, and let it figure out the steps itself.

That's what an agent is. Not a smarter autocomplete — a loop that reads files, runs checks, makes decisions, and calls your code until the job is done.

In this article, I'll walk through building a TypeScript code review agent using Anthropic's SDK. It will autonomously scan your project, find issues, and output a structured report — without you prompting it at each step.


What Makes Something an "Agent"

A regular API call is stateless: you send a prompt, you get a response. An agent is different in three ways:

  1. Tools — it can call functions you define (read a file, run a command, query an API)
  2. A loop — after using a tool, it sees the result and decides what to do next
  3. A goal — it keeps going until it reaches a terminal state, not until the context window fills up

The Anthropic SDK exposes this through tool_use content blocks. Claude returns a tool call, you execute it, you append the result, and Claude continues. You own the loop.


What We're Building

A CLI agent that takes a TypeScript project path and produces a code review report:

$ npx ts-node agent.ts ./src

🔍 Reading project structure...
📂 Found 12 TypeScript files
🔎 Checking src/services/UserService.ts...
⚠️  Found 3 issues in src/services/UserService.ts
✅ No issues in src/repositories/UserRepo.ts
...
📋 Report saved to review-report.md

Enter fullscreen mode Exit fullscreen mode

The agent decides which files to read, in what order, and how deep to go — we just give it the tools and the goal.


Project Setup

mkdir ts-review-agent && cd ts-review-agent
npm init -y
npm install @anthropic-ai/sdk
npm install -D typescript ts-node @types/node
npx tsc --init --strict --module commonjs --target es2020

Enter fullscreen mode Exit fullscreen mode

Create agent.ts:

import Anthropic from '@anthropic-ai/sdk';
import * as fs from 'fs';
import * as path from 'path';

const client = new Anthropic(); // reads ANTHROPIC_API_KEY from env

Enter fullscreen mode Exit fullscreen mode


Defining the Tools

The agent needs three capabilities: list files, read a file, and write the final report.

const tools: Anthropic.Tool[] = [
  {
    name: 'list_files',
    description: 'List all TypeScript files in a directory recursively',
    input_schema: {
      type: 'object',
      properties: {
        directory: { type: 'string', description: 'Absolute or relative path to directory' }
      },
      required: ['directory']
    }
  },
  {
    name: 'read_file',
    description: 'Read the contents of a TypeScript file',
    input_schema: {
      type: 'object',
      properties: {
        file_path: { type: 'string', description: 'Path to the file to read' }
      },
      required: ['file_path']
    }
  },
  {
    name: 'write_report',
    description: 'Write the final code review report to a markdown file',
    input_schema: {
      type: 'object',
      properties: {
        content: { type: 'string', description: 'Markdown content of the report' },
        output_path: { type: 'string', description: 'Where to save the report' }
      },
      required: ['content', 'output_path']
    }
  }
];

Enter fullscreen mode Exit fullscreen mode

Tool definitions are just JSON Schema — Claude reads the description to understand when and how to use each one. The descriptions matter more than you'd think.


Implementing the Tool Executor

type ToolInput = Record<string, string>;

function executeTool(name: string, input: ToolInput): string {
  switch (name) {
    case 'list_files': {
      const dir = input.directory;
      const files: string[] = [];
      function walk(current: string) {
        for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
          const full = path.join(current, entry.name);
          if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
            walk(full);
          } else if (entry.isFile() && entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) {
            files.push(full);
          }
        }
      }
      walk(dir);
      return JSON.stringify(files);
    }

    case 'read_file': {
      try {
        return fs.readFileSync(input.file_path, 'utf-8');
      } catch {
        return `Error: could not read ${input.file_path}`;
      }
    }

    case 'write_report': {
      fs.writeFileSync(input.output_path, input.content, 'utf-8');
      return `Report written to ${input.output_path}`;
    }

    default:
      return `Unknown tool: ${name}`;
  }
}

Enter fullscreen mode Exit fullscreen mode

This is intentionally simple. In production you'd add path sanitization, size limits, and timeouts — but the pattern is the same.


The Agent Loop

This is the core. Everything else is setup; this is where the agent runs.

async function runAgent(projectPath: string): Promise<void> {
  const messages: Anthropic.MessageParam[] = [
    {
      role: 'user',
      content: `You are a TypeScript code reviewer. Review the project at "${projectPath}".

Steps:
1. List all TypeScript files in the project
2. Read and review each file for: type safety issues, unused variables, any-typed params, missing error handling, and obvious logic bugs
3. Write a structured markdown report with findings, severity (error/warning/info), and suggested fixes

Be thorough but focus on real issues, not style preferences.`
    }
  ];

  console.log('🤖 Agent starting...
');

  while (true) {
    const response = await client.messages.create({
      model: 'claude-opus-4-7',
      max_tokens: 4096,
      tools,
      messages
    });

    // Add assistant response to history
    messages.push({ role: 'assistant', content: response.content });

    // Check if we're done
    if (response.stop_reason === 'end_turn') {
      console.log('
✅ Agent finished.');
      break;
    }

    // Process tool calls
    if (response.stop_reason === 'tool_use') {
      const toolResults: Anthropic.ToolResultBlockParam[] = [];

      for (const block of response.content) {
        if (block.type === 'tool_use') {
          console.log(`🔧 ${block.name}(${JSON.stringify(block.input).slice(0, 60)}...)`);
          const result = executeTool(block.name, block.input as ToolInput);
          toolResults.push({
            type: 'tool_result',
            tool_use_id: block.id,
            content: result
          });
        } else if (block.type === 'text' && block.text) {
          console.log(`💭 ${block.text.slice(0, 80)}...`);
        }
      }

      // Append tool results and continue
      messages.push({ role: 'user', content: toolResults });
    }
  }
}

// Entry point
const targetPath = process.argv[2] || '.';
runAgent(path.resolve(targetPath)).catch(console.error);

Enter fullscreen mode Exit fullscreen mode

The loop is simple: send messages → get response → if tool calls, execute them and append results → repeat until end_turn.


Running It

export ANTHROPIC_API_KEY=your_key_here
npx ts-node agent.ts ./src

Enter fullscreen mode Exit fullscreen mode

Output (truncated):

🤖 Agent starting...

🔧 list_files({"directory":"/Users/alex/project/src"}...)
🔧 read_file({"file_path":"/Users/alex/project/src/services/AuthService.ts"}...)
💭 Reviewing AuthService.ts — found potential issues with token expiry...
🔧 read_file({"file_path":"/Users/alex/project/src/middleware/auth.ts"}...)
🔧 write_report({"content":"# Code Review Report

## Summary...","output_p}...)

✅ Agent finished.

Enter fullscreen mode Exit fullscreen mode

The agent reads files in an order it decides, cross-references related files, and writes a cohesive report — without you prompting each step.


Patterns That Matter in Production

1. Token budget awareness. Each iteration appends to messages. For large codebases, you'll hit limits fast. Either batch files (give the agent 5 files per run) or summarize intermediate results.

// Rough token estimate before each request
const estimatedTokens = JSON.stringify(messages).length / 4;
if (estimatedTokens > 150_000) {
  // Summarize or paginate
}

Enter fullscreen mode Exit fullscreen mode

2. Max iterations guard. Agents can loop unexpectedly. Add a hard limit:

let iterations = 0;
while (iterations++ < 20) { ... }

Enter fullscreen mode Exit fullscreen mode

3. Structured tool results. Return JSON from tools, not prose. Claude parses structured data more reliably than free text.

4. System prompt for persona. Move the role description out of the user message into a system parameter — it's more robust and doesn't count against your conversation history structure.


Key Takeaways

  • An agent is just a loop: model → tool calls → results → model, until stop_reason === 'end_turn'
  • Tool descriptions are part of your prompt — write them like documentation
  • You own the loop, which means you control retries, limits, and error handling
  • The Anthropic SDK exposes everything you need — no framework required for basic agents
  • Start with 2-3 well-defined tools and expand; generic "execute_code" tools cause unpredictable behavior

The full code for this agent is ~120 lines of TypeScript. The complexity in real agents comes from state management, error recovery, and tool design — not from the loop itself.


Follow me on Twitter @Alex_Rogov_js for more AI + Architecture content. If you found this useful, check out my other articles on AI-friendly TypeScript project structure and what I put in every CLAUDE.md.


Originally published on my Hashnode blog. Follow me for more AI + Architecture content.