AI 에이전트 시스템(특히 Claude / Cursor / Anthropic ecosystem)에서 기본 개념인 Agent, Skill, Rule, CLAUDE.md 외에, 실무에서 고성능 AI 개발 환경을 구축할 때 반드시 함께 조합해 사용하는 핵심 개념 4가지가 있습니다.
새롭게 알아두어야 할 핵심 요소는 Context File (Prompt Context), System Prompt / Role, Tool / Function, Workflow (Pipeline) 입니다.
전체 구조에서의 역할과 개별 요소의 목적, 사용 방법, 작성 전략을 한눈에 정리해 드립니다.
1. AI 제어 시스템 전체 구조 한눈에 보기
| CLAUDE.md | 최상위 행동 지침 및 규칙 모음 | 회사 사규 및 가이드북 | CLAUDE.md, .cursorrules |
| Agent | 자율적 판단과 도구 사용 능력을 가진 주체 | 담당 직원 | 시스템 프롬프트 + Tool 세트 |
| Skill | 특정한 목적을 달성하는 재사용 모듈 | 직원의 전문 직무 기술 | 프롬프트 템플릿, 스크립트 |
| Rule | 지켜야 할 엄격한 제약/조건 | 보안 및 규정 준수 가이드 | Markdown 내 조건문, Checklist |
| Context (추가) | 작업을 수행하는 데 필요한 현재 정보 | 업무용 참조 문서 / 배경지식 | 프로젝트 코드, 문서 데이터 |
| Tool (추가) | 외부 세계와 상호작용하는 기능 | 컴퓨터, 계산기, API | Python 함수, Open API |
| Workflow (추가) | 순차적/병렬적 작업 처리 흐름 | 업무 프로세스 (SOP) | Chain, DAG 구조 |
2. 기존 4가지 요소 정리 (Agent, Skill, Rule, CLAUDE.md)
① CLAUDE.md
- 목적: 프로젝트 디렉터리 루트에 위치하며, AI가 작업 환경을 해석할 때 가장 먼저 읽는 최상위 지침 파일입니다.
- 사용 방법: 코딩 스타일, 프로젝트 빌드/테스트 명령어, 자주 발생하는 오류 처리 방침을 적어둡니다.
- 작성 예시:
-
Markdown
# Project Guidelines - Node version: 18+ - Style: Use TypeScript strict mode, functional components only. - Commands: - Build: `npm run build` - Test: `npm run test`
② Agent
- 목적: 목표가 주어졌을 때 스스로 계획을 수립하고, 도구를 선택하여 문제를 해결하는 주체입니다.
- 사용 방법: 특정 역할(예: "코드 리뷰어", "데이터 분석가")을 부여하고 도구 접근 권한을 지정합니다.
③ Skill
- 목적: AI가 반복적으로 수행해야 하는 특정 작업 템플릿이나 전용 알고리즘을 모듈화한 것입니다.
- 사용 방법: "API 문서 작성 Skill", "오류 로그 분석 Skill" 등으로 분리하여 필요할 때 호출합니다.
④ Rule
- 목적: AI의 환각(Hallucination)을 줄이고 정해진 출력 방식을 강제하기 위한 하드 제약 조건입니다.
- 사용 방법: MUST, NEVER와 같이 명확한 어조로 작성합니다. (예: "절대로 테스트 코드를 생략하지 마라.")
3. 새로 알아야 할 핵심 추가 개념 4가지
⑤ Context (문맥 / 배경 정보)
- 목적: AI에게 작업 대상이 되는 구체적인 정보(코드베이스, 기존 문맥, 요구사항)를 제공하여 정확도를 극대화합니다.
- 사용 방법: 프롬프트에 작성하거나 vector DB(RAG)를 사용해 관련 문서만 추출하여 주입합니다.
- 작성 전략:
-
Markdown
## Current Context - Target Framework: Next.js 14 (App Router) - Current File State: User Authentication Module - User Constraints: Must use JOSE library for JWT.
⑥ Tool / Function Calling (도구 사용)
- 목적: AI가 텍스트 생성을 넘어 파일 읽기/쓰기, 웹 검색, 터미널 명령 실행, Database 조회 등 실제 액션을 취할 수 있게 합니다.
- 사용 방법: AI에게 사용 가능한 함수 이름과 파라미터 규격(JSON Schema)을 전달합니다.
- 작성 전략 (JSON Schema 형태):
-
JSON
{ "name": "run_terminal_command", "description": "Executes a shell command in the project root.", "parameters": { "type": "object", "properties": { "command": { "type": "string" } }, "required": ["command"] } }
⑦ System Prompt / Persona (시스템 프롬프트)
- 목적: Agent의 근본적인 성격, 역량 한계, 응답 톤앤매너를 규정하는 백그라운드 명령어입니다.
- 사용 방법: 대화가 시작되기 전 AI 엔진의 최상단 제어 레이어로 입력합니다.
- 작성 전략:
-
Markdown
You are a Senior Security Engineer. Your task is to review the code and report vulnerabilities strictly based on OWASP Top 10. Always answer in concise Korean with bullet points.
⑧ Workflow / Orchestration (파이프라인)
- 목적: 복잡한 대형 과제를 여러 Agent나 Skill이 단계별로 협력하도록 설계하는 실행 순서 구조입니다.
- 사용 방법: 기획 Agent → 개발 Skill → 검증 Rule 순으로 연결하여 자동화합니다.
- 작성 전략 (실행 가이드 형태):
-
Step 1. Read CLAUDE.md to understand code rules. Step 2. Use Search Tool to identify affected files. Step 3. Apply Code Modification Skill. Step 4. Run Test Tool to verify fix.
4. 모든 요소를 종합한 올바른 활용법
실무 애플리케이션이나 개발 환경을 구축할 때는 이 요소들을 다음과 같이 조합하여 사용합니다.
[Project Root]
└── CLAUDE.md (프로젝트 전역 최상위 규칙)
[Execution Pipeline / Workflow]
├── Agent (역할 부여: Senior Developer)
├── Context (작업 범위: /src/auth 코드)
├── Skill (작업 기술: Refactoring Pattern)
├── Rule (제약: No Breaking Changes)
└── Tool (도구: File Editor, Git Command)
- CLAUDE.md에 기본 프로젝트 가이드를 작성해 둡니다.
- 특정 작업을 수행할 때 Agent를 호출하고 System Prompt로 역할을 정합니다.
- 작업에 필요한 Context와 Tool을 제공합니다.
- 작업 품질을 유지하기 위해 Rule과 Skill을 적용하여 Workflow에 따라 순차 실행하게 합니다.
-------------------------------------------------------------------------
실제 복잡한 대형 프로젝트(예: Next.js + Nest.js/FastAPI + Monorepo 구조)에서 바로 사용할 수 있는 CLAUDE.md 범용 풀 버전 템플릿과 실제 적용 예시입니다.
CLAUDE.md는 Claude Code CLI나 Cursor 등의 AI 에이전트가 프로젝트 디렉터리에 진입할 때 가장 먼저 읽는 Context이자 시스템 규칙 문서이므로, 가독성이 높고 규칙이 명확해야 환각(Hallucination)을 줄일 수 있습니다.
1. Production-Ready CLAUDE.md 작성 템플릿
프로젝트 루트에 CLAUDE.md 파일을 생성하고 아래 구조를 복사하여 프로젝트에 맞게 수정해 사용할 수 있습니다.
# [Project Name] - AI Agent Guidelines
## 1. Project Overview & Tech Stack
- **Architecture**: [e.g., Monorepo / Microservices / Layered Architecture]
- **Frontend**: [e.g., Next.js 14 (App Router), TypeScript, TailwindCSS, TanStack Query]
- **Backend**: [e.g., NestJS, TypeScript, PostgreSQL, Prisma ORM]
- **Environment**: Node v20+, pnpm v9+
---
## 2. Core Operating Rules (CRITICAL)
- **Language**: Always write comments, commit messages, and documentations in **English**. Explain explanations and answers to the user in **Korean**.
- **No Assumptions**: Do NOT hallucinate APIs, packages, or database schemas. Check the codebase first.
- **Scope Restriction**: Modify ONLY the files required for the specified task. Do NOT refactor unrelated code.
- **Safety**: NEVER delete or expose credentials (`.env` files, API keys).
---
## 3. Essential Commands
### Build & Run
- Install Dependencies: `pnpm install`
- Dev Server (All): `pnpm dev`
- Dev Frontend Only: `pnpm --filter web dev`
- Dev Backend Only: `pnpm --filter api dev`
### Quality Assurance & Testing
- Linting: `pnpm lint`
- Type Check: `pnpm type-check`
- Unit Tests: `pnpm test`
- Single Test File Run: `pnpm test -- [path/to/test-file]`
- Build Check: `pnpm build`
---
## 4. Coding Standards & Conventions
### General Concepts
- Write clean, self-documenting code.
- Prefer functional programming and immutability over imperative mutation.
- Use explicit type definitions (`interface` over `type` for objects). Do NOT use `any`.
### Directory Structure Guidelines
- `/apps/web`: Frontend application
- `/apps/api`: Backend application
- `/packages/ui`: Shared UI components
- `/packages/types`: Shared TypeScript interfaces/types
### Code Style Examples
```typescript
// GOOD: Explicit return types, early returns, no implicit 'any'
export async function getUserProfile(userId: string): Promise<UserProfile null |> {
if (!userId) return null;
const user = await db.user.findUnique({ where: { id: userId } });
return user ? mapToProfile(user) : null;
}
// BAD: Avoid 'any', nested callbacks, side-effects in getters
export async function getUserProfile(userId: any) { ... }
5. Workflow & Execution Checklist
When asked to implement a new feature or fix a bug, follow this exact sequence:
- Context Gathering: Search existing files to understand current implementation.
- Implementation:
- Keep changes atomic and focused.
- Follow existing patterns in the codebase.
- Verification:
- Run pnpm type-check to ensure no TypeScript errors.
- Run relevant unit tests using pnpm test.
- Completion: Summarize changes concisely in Korean.
---
## 2. 실제 적용 예시 (E-Commerce Monorepo 프로젝트)
이해를 돕기 위해 실무 전자상거래 플랫폼 프로젝트 스타일로 완성된 예시입니다.
```markdown
# ShopX Monorepo - Claude Agent Guidelines
## 1. Overview & Stack
ShopX is an enterprise e-commerce platform.
- **Framework**: Next.js 14 (App Router) + NestJS (REST API)
- **Database**: PostgreSQL with Prisma ORM
- **Package Manager**: `pnpm` (Workspace Enabled)
---
## 2. Strict Rules
1. **Response Language**: Technical explanations to user in **Korean**, code/comments/commits in **English**.
2. **Type Safety**: `strict: true` is enforced. Never use `any` or `@ts-ignore`.
3. **Prisma Operations**: Never execute direct raw SQL queries. Use Prisma Client.
4. **Git Discipline**: Do not execute `git commit` or `git push` unless explicitly instructed.
---
## 3. Command Matrix
| Task | Command |
| :--- | :--- |
| **Setup** | `pnpm install` |
| **Dev Mode** | `pnpm dev` |
| **Linting** | `pnpm lint --fix` |
| **Type Check** | `pnpm --filter @shopx/web typecheck` |
| **Prisma Migration** | `pnpm --filter @shopx/api exec prisma migrate dev` |
| **Run Unit Tests** | `pnpm test` |
---
## 4. Architecture Constraints
### Frontend (`/apps/web`)
- Use Server Components by default. Add `'use client'` only when interactive hooks (`useState`, `useEffect`) are necessary.
- UI components must strictly use TailwindCSS and Lucide Icons.
### Backend (`/apps/api`)
- Follow NestJS standard module structure (`Controller` -> `Service` -> `Repository`).
- All DTOs must use `class-validator` for request validation.
---
## 5. Standard Task Workflow
Before marking a task as resolved, you **MUST** run:
1. `pnpm typecheck`
2. `pnpm test`
If any of these fail, fix the errors before concluding your response.
💡 CLAUDE.md 활용 팁
- 너무 길지 않게 유지: 문서가 너무 길어지면 AI가 지침을 간과(Prompt Drift)할 수 있으므로 핵심 규칙 위주로 짧고 명확하게 작성합니다.
- 명령어 표기: AI가 직접 실행(Bash Tool 등)할 가능성이 높으므로, 명령어는 복사해 바로 실행할 수 있도록 정확히 표기해 주는 것이 좋습니다.
- 프로젝트 최상단 배치: 파일 이름은 정확히 CLAUDE.md로 프로젝트 루트 경로에 위치시켜야 자동 인식됩니다.
------------------------------------------------------
AI Agent가 사용자 요청을 분석하고, 필요한 Tool(도구/함수)을 선택해 실행한 뒤, 최종 결과를 조합하여 답변하는 기본 구조(ReAct/Tool-calling Loop)입니다.
이해하기 쉬우면서도 실제 서비스 구현에 바로 사용할 수 있는 TypeScript와 Python 예시 코드를 각각 작성했습니다.
1. TypeScript 예시 (Anthropic SDK)
Anthropic 공식 SDK(@anthropic-ai/sdk)를 사용하여 Agent가 계산기 Tool을 호출하는 흐름입니다.
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
// 1. Tool 실제 실행 로직 (Local Function)
function addNumbers(a: number, b: number): number {
return a + b;
}
// 2. Claude에게 전달할 Tool Definition (JSON Schema)
const tools: Anthropic.Tool[] = [
{
name: "add_numbers",
description: "Adds two numbers together and returns the result.",
input_schema: {
type: "object",
properties: {
a: { type: "number", description: "First number" },
b: { type: "number", description: "Second number" },
},
required: ["a", "b"],
},
},
];
// 3. Agent Loop (Tool Calling Handling)
async function runAgent(userPrompt: string) {
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: userPrompt },
];
console.log(`[User]: ${userPrompt}`);
// 1차 요청: 사용자 질문 + 사용 가능한 Tool 목록 전달
let response = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
tools: tools,
messages: messages,
});
// Agent가 Tool을 사용하기로 판단했는지 확인 (stop_reason === 'tool_use')
if (response.stop_reason === "tool_use") {
// 응답 메시지를 대화 기록에 추가
messages.push({ role: "assistant", content: response.content });
// 요청된 Tool 찾아 실행
for (const block of response.content) {
if (block.type === "tool_use") {
const { name, input, id } = block;
console.log(`[Agent Action]: Tool '${name}' 호출 요청함`, input);
let toolResult = 0;
if (name === "add_numbers") {
const { a, b } = input as { a: number; b: number };
toolResult = addNumbers(a, b);
}
// Tool 실행 결과를 Agent에게 전달하기 위한 메시지 생성
messages.push({
role: "user",
content: [
{
type: "tool_result",
tool_use_id: id,
content: String(toolResult),
},
],
});
}
}
// 2차 요청: Tool 실행 결과를 대화 기록에 포함하여 최종 답변 생성
const finalResponse = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
tools: tools,
messages: messages,
});
console.log(`[Agent Final Answer]:`);
console.log(finalResponse.content[0]);
} else {
// Tool 사용 없이 바로 답변한 경우
console.log(`[Agent Answer]:`, response.content[0]);
}
}
// 실행 예시
runAgent("12345 더하기 67890 결과가 뭐야?");
2. Python 예시 (Anthropic SDK)
동일한 메커니즘을 Python 코드로 구현한 버전입니다.
import os
import json
import anthropic
client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
# 1. Tool 실제 실행 함수
def add_numbers(a: float, b: float) -> float:
return a + b
# 2. Tool 스펙 정의
tools = [
{
"name": "add_numbers",
"description": "Adds two numbers together and returns the result.",
"input_schema": {
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["a", "b"]
}
}
]
def run_agent(user_prompt: str):
messages = [{"role": "user", "content": user_prompt}]
print(f"[User]: {user_prompt}")
# 1차 API 호출: Agent가 도구를 사용할지 판단
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
tools=tools,
messages=messages
)
# Agent가 Tool 사용을 요청한 경우
if response.stop_reason == "tool_use":
# Assistant의 응답(Tool 호출 요청)을 대화 내역에 누적
messages.append({"role": "assistant", "content": response.content})
# 호출할 Tool 탐색 및 실행
for block in response.content:
if block.type == "tool_use":
tool_name = block.name
tool_input = block.input
tool_use_id = block.id
print(f"[Agent Action]: '{tool_name}' 실행 중...", tool_input)
# 실제 파이썬 함수 실행
result = 0
if tool_name == "add_numbers":
result = add_numbers(tool_input["a"], tool_input["b"])
# Tool 실행 결과를 user 역할로 메시지에 추가
messages.append({
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": str(result)
}
]
})
# 2차 API 호출: Tool 결과를 바탕으로 최종 문장 생성
final_response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
tools=tools,
messages=messages
)
print("[Agent Final Answer]:")
print(final_response.content[0].text)
else:
print("[Agent Answer]:", response.content[0].text)
# 실행 예시
if __name__ == "__main__":
run_agent("12345 더하기 67890 계산해줘.")
💡 핵심 동작 원리 (ReAct 패턴)
[사용자 질문]
↓
1. [Agent에게 전달] (질문 + 사용 가능한 Tool Schema)
↓
2. [Agent의 판단] "내가 계산할 수 없으니 'add_numbers' Tool을 써야겠다!"
↓
3. [Agent 응답] stop_reason: "tool_use" / 파라미터: { a: 12345, b: 67890 }
↓
4. [개발자 코드 실행] 로컬 함수 add_numbers(12345, 67890) 실행 -> 결과: 80235
↓
5. [Agent에게 결과 전달] tool_result: "80235"
↓
6. [Agent의 최종 답변] "12345와 67890을 더한 결과는 80,235입니다."
이 구조를 다중 루프(while 문)로 감싸면 Tool을 수차례 연속해서 호출하는 자율형 에이전트(Autonomous Agent)로 확장할 수 있습니다.
'프로그램 활용 > 인공지능(AI)' 카테고리의 다른 글
| LLM과 RAG 환경 구축 (0) | 2026.08.04 |
|---|---|
| AI | LanceDB란 (0) | 2026.08.04 |
| 그래프 엔지니어링이란? 2026년 AI 에이전트 오케스트레이션의 새 계층과 도입 판단 기준 (0) | 2026.07.30 |
| n8n 활용 방법 (0) | 2026.07.28 |
| AI가 문맥을 오해하지 않고 가장 빠르고 정확하게 파악할 수 있도록 하는 마크다운(Markdown) 기반의 문의 내용 작성 예시 (0) | 2026.07.01 |