실전 · CH06

미니 프로젝트: 11월 매출 리포트

지금까지 배운 것을 한 파일에 묶습니다. 에이전트는 회사 도구로 숫자를 조회하고, 달성률 표를 만들어 파일로 저장합니다. 마지막에 그 숫자를 우리가 직접 검증합니다.


1. 설계: 무엇을 주고 무엇을 막을까

주는 것

매출 조회·목표 조회 도구(4장), 파일 저장 Write 하나.

막는 것

Bash, Edit, 웹 검색은 목록에서 뺍니다. 필요 없는 도구는 주지 않는 것이 가장 확실한 안전장치입니다.

정하는 것

시스템 프롬프트로 리포트 구성과 "숫자는 도구 결과만" 규칙, 턴·비용 상한.

2. 전체 코드

06_project.py
"""미니 프로젝트: 11월 매출 리포트 에이전트 (내 도구 + 파일 저장 + 안전장치)"""
import asyncio
from pathlib import Path
from typing import Any
from claude_agent_sdk import (
    tool, create_sdk_mcp_server, query, ClaudeAgentOptions,
    AssistantMessage, ResultMessage, ToolUseBlock,
)
from sales_data import revenue_by, monthly_target


@tool("revenue_by", "매출 합계. group_by=branch/product/month, month='2026-11' 형식(비우면 전체)",
      {"group_by": str, "month": str})
async def revenue_by_tool(args: dict[str, Any]) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": str(revenue_by(args["group_by"], args.get("month", "")))}]}


@tool("monthly_target", "지점의 2026년 11월 매출 목표(원)", {"branch": str})
async def monthly_target_tool(args: dict[str, Any]) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": str(monthly_target(args["branch"]))}]}


SYSTEM = """너는 팝콘상사 매출 리포트 담당이야.
- 숫자는 반드시 도구 결과만 쓴다. 직접 더하거나 추정하지 않는다.
- 리포트는 report_2026-11.md 파일 하나로 저장한다.
- 리포트 구성: 지점별 11월 매출, 목표, 달성률(%) 표 / 상품별 11월 매출 / 한 줄 요약."""


async def main():
    server = create_sdk_mcp_server(name="sales", version="1.0.0",
                                   tools=[revenue_by_tool, monthly_target_tool])
    options = ClaudeAgentOptions(
        system_prompt=SYSTEM,
        tools=["Write"],
        mcp_servers={"sales": server},
        allowed_tools=["mcp__sales__revenue_by", "mcp__sales__monthly_target", "Write"],
        permission_mode="acceptEdits",
        max_turns=15,
        max_budget_usd=1.00,
    )
    async for message in query(prompt="2026년 11월 매출 리포트를 만들어 줘.", options=options):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, ToolUseBlock):
                    print("[도구]", block.name, str(block.input)[:80])
        elif isinstance(message, ResultMessage):
            print("[끝]", message.subtype, "| 비용(USD):", message.total_cost_usd)

    report = Path("report_2026-11.md")
    print("\n--- 저장된 리포트 ---\n" + (report.read_text(encoding="utf-8") if report.exists() else "(파일 없음)"))


asyncio.run(main())

3. 실행하고 리포트를 엽니다

python 06_project.py
[도구] mcp__sales__revenue_by {'group_by': 'branch', 'month': '2026-11'} [도구] mcp__sales__monthly_target {'branch': '강남점'} [도구] mcp__sales__monthly_target {'branch': '홍대점'} [도구] mcp__sales__monthly_target {'branch': '판교점'} [도구] mcp__sales__revenue_by {'group_by': 'product', 'month': '2026-11'} [도구] Write {'file_path': '.../report_2026-11.md', ...} [끝] success | 비용(USD): 0.0… --- 저장된 리포트 --- # 2026년 11월 매출 리포트 | 지점 | 매출 | 목표 | 달성률 | ...

4. 검증: 이 숫자와 같아야 합니다

리포트가 그럴듯해 보여도 숫자는 따로 확인합니다. sales.csv를 직접 계산한 정답은 아래와 같습니다. 11월 상품별로는 콤보 세트가 7,404,000원으로 1위입니다.

지점11월 매출11월 목표달성률
강남점5,808,0005,500,000105.6%
홍대점5,371,0005,500,00097.7%
판교점3,991,5004,500,00088.7%

참고로 이 교안을 만들며 작은 로컬 모델(qwen2.5 7B)로 이 파일을 그대로 돌렸을 때 저장된 리포트의 앞부분입니다. 숫자는 모두 도구에서 왔고 정답표와 같았습니다. 달성률 자릿수(105.55)처럼 형식은 모델마다 달라지니, 원하는 형식이 있다면 시스템 프롬프트에 적습니다.

### 2026년 11월 매출 리포트 | 지점 | 목표 (원) | 매출 (원) | 달성률 (%) | | 강남점 | 5,500,000 | 5,808,000 | 105.55 | | 홍대점 | 5,500,000 | 5,371,000 | 97.65 | | 판교점 | 4,500,000 | 3,991,500 | 88.70 | #### 상품별 11월 매출 | 상품 | 매출 (원) | | 콤보 세트 | 7,404,000 | | 치즈 팝콘 | 4,263,000 | | 카라멜 팝콘 | 3,503,500 |
스스로 점검

5. 더 해 보기

이것만 기억하세요

필요한 도구만 주고, 숫자는 도구가 계산하게 하고, 결과는 원본 계산과 대조합니다. 에이전트가 만든 표를 그대로 보고서에 쓰지 않습니다.

다음
07. 운영 전 점검과 SDK 고르기
이어보기 →