Engineering

Claude Agent Thực Sự Hoạt Động Như Thế Nào: Phân Tích Kiến Trúc 6 Tầng

By Ginbok10 min read
Hầu hết developer khi lần đầu xây dựng agent LLM đều mang theo một mental model sai: model chạy code. Không phải vậy. Hiểu rõ ranh giới thực sự — Anthropic's infrastructure xử lý gì so với những gì chạy trong environment của bạn — là sự khác biệt giữa một demo mong manh và một agent production-grade.

Bài này sẽ đi qua toàn bộ Claude agent stack theo sáu tầng, từ prompt của developer đến private network target. Mỗi quyết định kiến trúc đều có lý do. Chúng ta sẽ đi qua tất cả.

TẦNG 1 · DEVELOPER Developer prompt / task / @claude HTTPS TẦNG 2 · ĐIỂM VÀO Claude.ai Web / Desktop / Mobile Claude in Chrome / Excel Tích hợp Slack / GitHub Actions IDE plugins (MCP client) API / Claude Code api.anthropic.com/v1 SDK: Python / TS / Java TẦNG 3 · ANTHROPIC CLOUD · Control Plane Anthropic Cloud · Constitutional AI · ZDR · Prompt Caching · Batch API Model Router Haiku · Sonnet · Opus think → tool_use → observe Extended thinking (Opus) Prompt cache: giảm 90% chi phí Batch API: giảm 50% chi phí claude-sonnet-4-5 / opus-4 claude-haiku-4-5-20251001 Project / Context Mgr system prompt · memory Claude Projects (knowledge) MCP remote proxy (HTTP/SSE) Tool schema registry Rate limits · billing tiers console.anthropic.com Safety Gateway API Router · output filter api.anthropic.com Constitutional AI layer Không exec tool trên Anthropic tool_use → JSON về client bedrock.amazonaws.com (AWS) aiplatform.googleapis.com (GCP) tool_use JSON block TẦNG 4 · EXECUTOR RUNTIME · chọn một · outbound-only Môi trường của bạn · Anthropic không bao giờ chạy tool của bạn A · Claude Code local dev · mặc định npx claude-code full FS + bash access không cần inbound port nhanh nhất cho cá nhân B · SDK Agent Python / TS / Java Anthropic() client tool_use loop trong code server deploy · long-running + MCP stdio / HTTP C · Self-hosted MCP Fleet team / enterprise MCP HTTP/SSE servers private tools + secrets OAuth 2.1 / API key auth đăng ký trong Projects D · Bedrock / Vertex cloud-managed AWS Bedrock Agents GCP Vertex AI Claude IAM + VPC · autoscaled data ở lại region của bạn TẦNG 5 · THỰC THI TOOL Agent Loop · nhận tool_use · thực thi · trả tool_result Bash exec · build · test Filesystem đọc · ghi · patch Web Search grounding · fetch MCP Servers custom tool providers Computer Use screenshot · click Custom bất kỳ function TẦNG 6 · TARGETS Private Network mode B / C / D · ở trong infra của bạn · Git clone R/W · feature branches · Build cache · package registries · Internal APIs · DB · staging Repo / secret không rời khỏi network của bạn GitHub / GitLab · Branch push + PR open · Webhook về agent · Submodules + deps Azure DevOps / Bitbucket Artifacts / Outputs · claude.ai Artifacts (HTML/JSX) · File: docx / pdf / xlsx · Code files to /outputs · Computer Use screenshots Served via claude.ai sandbox

Insight quan trọng nhất

Infrastructure của Anthropic chỉ làm một việc: chạy model. Nó sinh ra text. Khi text đó chứa một tool_use block, block đó được serialize thành JSON và trả về cho ai gọi API. Code của bạn chạy tool. Không phải Anthropic.

Đây không phải chi tiết implementation nhỏ. Nó quyết định toàn bộ security posture, network topology, và câu chuyện compliance của bạn. Database credentials, internal API endpoints, filesystem của bạn — không cái nào chạm tới server của Anthropic.

Tầng 1–2: Điểm vào

Developer tiếp cận Claude qua ba bề mặt: sản phẩm Claude.ai (web, desktop, mobile, browser extension, Office integrations), các tích hợp first-party như Slack hoặc GitHub Actions, và API trực tiếp qua SDK hoặc Claude Code CLI. Cả ba đều hội tụ về cùng một control plane bên dưới.

Sự khác biệt thực tế là về context: Claude.ai quản lý system prompt và conversation cho bạn. API cho bạn full control. Claude Code là API với một tool executor được built-in sẵn — đây là con đường nhanh nhất từ "tôi muốn một agent" đến chạy code trên máy của bạn.

Tầng 3: Control plane — Anthropic thực sự làm gì

Ba subsystem chạy bên trong Anthropic's cloud, không cái nào execute tool của bạn:

Model Router chọn và chạy model. Haiku cho tác vụ latency-sensitive, Sonnet là workhorse mặc định, Opus khi cần extended thinking. Prompt caching ở đây rất đáng kể: cache hit giảm chi phí đến 90% và latency đến 85%. Nếu system prompt của bạn dài và ổn định — pattern phổ biến trong agentic setups — caching tự khấu hao ngay lập tức.

Project / Context Manager duy trì system prompt, knowledge đính kèm, và MCP tool schema registry. Claude Projects hoạt động như một persistent memory layer qua các session. Remote MCP server được đăng ký ở đây được proxy qua HTTP/SSE — model biết về các tool mà không cần tool server phải expose ra internet trực tiếp.

Safety Gateway filter mọi response qua Constitutional AI trước khi rời khỏi network của Anthropic. Nó cũng xử lý routing đến AWS Bedrock và GCP Vertex AI cho khách hàng có yêu cầu data residency. Khi model quyết định gọi một tool, gateway serialize quyết định đó thành một tool_use content block và trả về. Đó là ranh giới.

Tầng 4: Executor runtime — nơi tool calls hạ cánh

Đây là tầng hầu hết team specify không đủ. Bốn mode, mỗi mode có tradeoff khác nhau:

Mode Setup Phù hợp cho Data residency
A · Claude Code npx @anthropic-ai/claude-code Dev cá nhân Máy của bạn
B · SDK Agent Python/TS client loop Custom workflow Server của bạn
C · MCP Fleet HTTP/SSE MCP servers Chia sẻ tool cả team Infra của bạn
D · Bedrock/Vertex Cloud-managed Enterprise / regulated Region AWS/GCP của bạn

Decision tree: Một developer trên máy local? → Mode A. Custom business logic, chạy trên server? → Mode B. Team cần shared private tools (internal DB, ticketing, code review)? → Mode C. Ngành regulated hoặc yêu cầu data residency? → Mode D.

Cả bốn mode đều có chung property về security: outbound-only đến api.anthropic.com. Không cần inbound connection, không cần public IP trên executor.

Tầng 5: Vòng lặp tool_use

Agent loop là một while-loop đơn giản mà hầu hết developer viết sai lần đầu.

❌ Phiên bản naive — vỡ trên multi-step tasks:

# Sai: single-shot, bỏ qua tool_use
response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": user_prompt}]
)
# Chỉ xử lý response đầu tiên — nếu model trả về
# tool_use, bạn không bao giờ execute nó và task bị bỏ dở.

✅ Vòng lặp đúng:

import anthropic

client = anthropic.Anthropic()

def run_agent(user_prompt: str, tools: list, tool_executor: dict) -> str:
    messages = [{"role": "user", "content": user_prompt}]

    while True:
        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=4096,
            tools=tools,
            messages=messages,
        )

        # Append toàn bộ assistant response (có thể chứa mixed blocks)
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason == "end_turn":
            # Lấy text response cuối cùng
            for block in response.content:
                if block.type == "text":
                    return block.text
            return ""

        if response.stop_reason == "tool_use":
            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    fn = tool_executor.get(block.name)
                    result = fn(**block.input) if fn else f"Unknown tool: {block.name}"
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": str(result),
                    })
            # Đưa kết quả trở lại — vòng lặp tiếp tục
            messages.append({"role": "user", "content": tool_results})
            continue

        # stop_reason không mong đợi (max_tokens, stop_sequence, v.v.)
        break

    return ""

Ba điểm cần chú ý về phiên bản đúng:

  1. Toàn bộ list response.content được append nguyên vẹn vào message history. Bỏ non-text blocks sẽ phá conversation state.
  2. Tool results được trả về trong một user turn, bọc trong tool_result blocks và khóa bằng tool_use_id. Thiếu ID này gây validation error.
  3. Vòng lặp exit khi end_turn, không phải khi "không còn tool call nữa." Model quyết định khi nào nó xong.

Tầng 6: Targets — tool thực sự chạm vào gì

Tùy theo executor mode, tool của agent chạm vào ba loại target:

Private network (mode B, C, D): Git repository, build cache, internal API, database, staging environment. Data này không bao giờ rời khỏi infrastructure của bạn. Thứ duy nhất đi sang Anthropic là giá trị trả về của tool — một string hoặc JSON blob. Thiết kế tool để trả về summary, không phải raw data dump, khi làm việc với nội dung nhạy cảm.

VCS: Agent push một branch, mở PR, và tùy chọn trigger webhook vòng lại vào agent. GitHub, GitLab, Azure DevOps, Bitbucket đều hoạt động. Agent không merge — quyết định đó thuộc về human reviewer.

Artifacts và outputs: Claude.ai render HTML và React artifact trong một sandboxed iframe. File output — document, spreadsheet, PDF — được ghi vào /outputs và serve để download. Computer Use screenshot trả về dưới dạng base64 image content block.

Tầng MCP protocol

Model Context Protocol là transport kết nối executor (Tầng 4) với tool providers (Tầng 5 trở đi). Nó xứng đáng được nêu riêng vì nó thay đổi cách bạn nghĩ về tool architecture.

Không có MCP, mọi tool là một function trong codebase của executor. Thêm tool nghĩa là thay đổi code và redeploy. Với MCP, tool là service. Tool database nội bộ của một team, tool code review, và tích hợp ticketing mỗi cái chạy như MCP server độc lập. Executor discover chúng qua schema registry. Thêm tool nghĩa là deploy một MCP server mới và đăng ký nó trong Claude Projects — không cần thay đổi executor.

Hai transport tồn tại: stdio (subprocess, dùng bởi Claude Code cho local tool) và HTTP/SSE (network, dùng cho remote MCP server và cloud proxy trong Claude Projects). Đối với team deployment, HTTP/SSE với OAuth 2.1 là lựa chọn đúng. Auth token không bao giờ đi qua hệ thống của Anthropic — nó được negotiate trực tiếp giữa executor và MCP server.

Zero Data Retention và câu chuyện compliance

ZDR có nghĩa là Anthropic không log, lưu trữ, hay train trên prompt và response của bạn. Nó có sẵn trên API theo thỏa thuận, và trên AWS Bedrock và GCP Vertex AI theo kiến trúc (data của bạn ở trong cloud account của bạn). Đối với ngành regulated — healthcare, finance, legal — Mode D (Bedrock/Vertex) với ZDR là cấu hình tiêu chuẩn.

Điểm tinh tế quan trọng: ZDR điều chỉnh những gì Anthropic lưu trữ. Nó không nói gì về những gì executor của bạn lưu trữ. Audit logging, request/response archiving, và PII scrubbing trong tool result là trách nhiệm của bạn ở Tầng 4.

Ý nghĩa trong thực tế

Khi bạn debug một agent bị lỗi, lỗi hầu như luôn ở một trong ba chỗ: vòng lặp tool_use không cycle đúng, tool result không được format thành tool_result block với đúng ID, hoặc system prompt không cho model đủ context để chọn đúng tool. Kiến trúc trên là ổn định. Logic vòng lặp và thiết kế tool là nơi công việc thực sự nằm.

Bắt đầu với Mode A (Claude Code) để validate tool design mà không cần ops overhead. Chuyển sang Mode B khi bạn cần phục vụ nhiều user hoặc chạy unattended. Thêm Mode C khi nhiều team cần truy cập vào cùng internal tool. Mode D khi legal nói vậy.

Model là phần dễ. Executor là nơi bạn kiếm lương.

]]>
#claude#anthropic#agent#architecture#MCP#claude-code#tool-use#agentic
← Back to Articles