MCP servers với Claude Code

4 — Mở rộng & Tự động hóaTrung cấp30 phút

Bài 4.2 đã giải thích tool use. Nhưng thực tế, tool built-in của Claude Code không cover được mọi trường hợp:

Bạn sẽ học được
  • Giải thích MCP là gì, vì sao Anthropic gọi nó là "USB-C cho AI"
  • Cài đặt MCP server (ví dụ Playwright) bằng claude mcp add
  • Cấu hình permission trong settings.local.json để tránh prompt mỗi lần
  • Sử dụng MCP server để Claude điều khiển browser, query DB, tương tác với tool ngoài
  • Chọn giữa CLI tool và MCP server cho task cụ thể

MCP là gì?

MCP = Model Context Protocol. Một giao thức mở (open protocol) do Anthropic công bố tháng 11/2024, cho phép:

Analogy "USB-C cho AI"

Trước: N AI tools × M services = N*M tích hợp cần maintain. Sau: N + M — ai cũng nói cùng "ngôn ngữ" MCP.

3 thứ MCP server có thể cung cấp

Trong thực tế, 90% MCP server cung cấp tools.

  • Bên thứ 3 tạo "MCP server" (cung cấp tool/resource/prompt)
  • Bất kỳ AI tool (Claude Code, Cursor, Claude Desktop, ChatGPT...) kết nối vào server đó
  • Không cần mỗi AI tool implement integration riêng
  • Tools — hàm Claude có thể gọi (browser.click, db.query, slack.send)
  • Resources — data Claude có thể đọc (like file but dynamic)
  • Prompts — template prompt đóng gói sẵn
┌────────────────────────────────────────────────────────────┐
│                                                            │
│  Trước MCP:                                                │
│                                                            │
│   [Claude Code]    [Cursor]    [Windsurf]    [Zed]        │
│        │              │            │           │          │
│        └──────────────┴────────────┴───────────┘          │
│                       │ (N × M custom integrations)        │
│   [GitHub]  [Linear]  [Slack]  [Postgres]  [Jira] ...     │
│                                                            │
│                                                            │
│  Với MCP:                                                  │
│                                                            │
│   [Claude Code]    [Cursor]    [Windsurf]    [Zed]        │
│        │              │            │           │          │
│        └──────────────┴──MCP───────┴───────────┘          │
│                       │ (N + M integrations)               │
│   [GitHub]  [Linear]  [Slack]  [Postgres]  [Jira] ...     │
│                                                            │
└────────────────────────────────────────────────────────────┘

Hệ sinh thái MCP hiện có

Một số MCP server phổ biến

ServerCapabilityDùng cho
@playwright/mcpBrowser automationTest UI, generate + compare visual
@anthropic/mcp-server-filesystemFilesystem opsRead/write file ngoài project
@anthropic/mcp-server-githubGitHub APIPR, issue, repo management
@anthropic/mcp-server-slackSlack APISend message, read channel
@anthropic/mcp-server-postgresPostgresQuery DB read-only
@linear-ai/mcpLinearTicket, project management
@notion/mcp-serverNotionRead/write Notion doc
@sentry/mcp-serverSentryError monitoring

Cài đặt MCP server: Ví dụ Playwright

Playwright MCP làm gì?

Playwright là library automation browser (Chromium, Firefox, WebKit). Playwright MCP wrap nó thành tool Claude có thể gọi:

Với Playwright MCP, Claude có thể: mở browser, điều hướng app của bạn, tương tác, và "thấy" kết quả — không cần bạn làm thủ công.

Bước 1: Cài server

Trong terminal (không phải Claude Code CLI):

Cú pháp: claude mcp add <name> <command> — gán cho server một tên và chỉ rõ cách start nó.

Bước 2: Verify

Trong Claude Code:

  • browser_snapshot — chụp UI hiện tại (text + a11y tree)
  • browser_click — click element
  • browser_type — gõ text vào input
  • browser_navigate — điều hướng URL
  • Và ~15 tool khác
  • name: "playwright" (tự chọn, dùng để reference)
  • command: npx @playwright/mcp@latest — Claude Code sẽ chạy command này để start server
claude mcp add playwright npx @playwright/mcp@latest

Bước 2: Verify

Bạn sẽ thấy:

/mcp

Cài đặt MCP server: Ví dụ Playwright (tiếp)

Bước 3: Hỏi Claude list tool

MCP Servers:
 - playwright  [connected, 16 tools available]

Bước 3: Hỏi Claude list tool

Claude sẽ list: mcp__playwright__browser_click, mcp__playwright__browser_snapshot, etc.

Bước 4: Cấu hình permission

Mặc định, Claude hỏi permission mỗi tool call. Với Playwright browser automation, có thể 50 tool call cho 1 task → 50 prompt permission = annoying.

Mở .claude/settings.local.json (tạo nếu chưa có):

What browser tools do you have access to now?

Bước 4: Cấu hình permission

Lưu ý: Pattern mcp__playwright match mọi tool từ Playwright MCP. Muốn chi tiết hơn:

{
  "permissions": {
    "allow": ["mcp__playwright"],
    "deny": []
  }
}

Cài đặt MCP server: Ví dụ Playwright (tiếp)

Rule: allow dùng mcp__<server>__<tool> hoặc mcp__<server> cho tất cả.

Bước 5: Restart Claude Code

Để reload settings. Sau đó dùng được Playwright tools mượt.

{
  "permissions": {
    "allow": [
      "mcp__playwright__browser_snapshot",
      "mcp__playwright__browser_navigate"
    ],
    "deny": ["mcp__playwright__browser_evaluate"]
  }
}

Ví dụ thực chiến: UI self-improving với Playwright MCP

Tình huống

Uigen generate React component từ prompt. Nhưng output khá generic: "purple-to-blue gradient", "standard Tailwind button". Muốn Claude tự cải thiện prompt generation thông qua observation.

Flow

Trong Claude Code (đã cài Playwright MCP):

Claude execute

Navigate to localhost:3000. Generate một basic pricing card. 
Sau đó:
1. Screenshot UI rendered
2. Nhận xét style hiện tại — tone, color, layout
3. Identify gì làm cho nó "generic AI-like"
4. Update @src/lib/prompts/generation.tsx để encourage 
   diversity hơn (original style, creative spacing, 
   asymmetric layout)
5. Test lại: generate một card nữa, compare before/after

Claude execute

Kết quả

Trong 3 phút, Claude đã:

Đây là kỹ thuật gọi là "self-improvement loop" — AI observe output của AI, cải tiến. Chỉ khả dụng nhờ MCP cho Claude khả năng "thấy" rendered UI.

  • Observe output thực tế (via browser)
  • Phân tích vấn đề
  • Edit prompt template
  • Verify improvement (via browser snapshot)
[mcp__playwright__browser_navigate] url: "http://localhost:3000"
[mcp__playwright__browser_type] text: "Create a pricing card 
  for a SaaS product with 3 tiers"
[mcp__playwright__browser_click] button: "Generate"
[Wait 3s for stream]
[mcp__playwright__browser_snapshot]

Observation: Card dùng gradient purple→blue mặc định, layout 
3 cột equal width, font Inter default, padding đều đặn. 
"Generic AI-like" — không có personality.

Problems:
- Gradient dùng quá phổ biến (purple-blue)
- Layout symmetric, không có visual hierarchy
- Không có unique accent element
- CTA button style default

[Read] src/lib/prompts/generation.tsx

Current prompt mà nói "create a modern card". Sẽ update để 
encourage diversity...

[Edit] src/lib/prompts/generation.tsx
  + Add diversity directives:
  + "Use unexpected color combinations: sunset (orange-pink-
     purple), ocean depth (teal-emerald-cyan), forest mist 
     (green-slate-stone)"
  + "Prefer asymmetric layouts — make one card taller or 
     wider to highlight"
  + "Use overlapping elements, non-uniform shadows"
  + "Avoid Inter as default font — suggest Instrument Serif 
     for titles, Geist Mono for numbers"

[mcp__playwright__browser_click] New Generation
[mcp__playwright__browser_snapshot]

Observation: Card mới có sunset gradient (orange→pink→violet), 
middle tier nhô cao hơn 10%, heading dùng serif italic, 
number dùng monospace. Hoàn toàn khác "default AI" trước.

CLI tool vs MCP server — Khi nào chọn gì?

Dev thường hỏi: "Tôi nên cài MCP server Linear, hay dùng linear CLI?"

Nguyên tắc từ Claude Code team

Lý do

CLI tool:

MCP:

Ví dụ cụ thể

  • Claude đã thấy trong training data → biết rất rõ
  • Output truyền thống (stdout/stderr) → Claude parse tốt
  • Không cần setup MCP
  • Có thể gọi từ Bash tool built-in
  • Thêm layer abstraction (server start, permission)
  • Protocol định nghĩa schema rõ → tốt cho integration structured
  • Cần khi capability không có CLI (ví dụ browser automation, real-time event)
NeedChọnLý do
GitHub PR managementgh CLIClaude biết gh rất rõ
Browser automationPlaywright MCPKhông có CLI equivalent đơn giản
Postgres querypsql CLIClaude thành thạo SQL + psql
Slack messageSlack MCPSlack API phức tạp, MCP wrap tốt
File ops ngoài projectFilesystem MCPSecurity bounded
Dockerdocker CLIClaude biết sâu
Custom internal APIMCP server riêngStructured + secured

Khám phá MCP ecosystem

Các category thường thấy

1. Developer tools

2. Databases

3. Productivity / SaaS

4. Cloud services

5. Domain-specific

Browse tại modelcontextprotocol.io/servers.

  • Playwright (browser), Puppeteer MCP
  • Chrome DevTools MCP
  • Filesystem MCP
  • GitHub MCP
  • Postgres MCP (read-only)
  • MongoDB MCP
  • Redis MCP
  • BigQuery MCP
  • Slack, Discord MCP
  • Google Drive, Notion MCP
  • Linear, Jira MCP
  • Figma MCP
  • AWS MCP (limited, focus EC2/S3)
  • Cloudflare MCP
  • GCP MCP
  • Stripe MCP (payment)
  • Sentry MCP (monitoring)
  • Terraform MCP (IaC)

Ví dụ thực chiến: Dev stack MCP cho fullstack dev

Setup điển hình

Dev fullstack Next.js + PostgreSQL + Vercel + Linear:

Use case 1: Debug production issue từ Sentry alert

# Browser automation cho E2E testing
claude mcp add playwright npx @playwright/mcp@latest

# Postgres read-only cho debug data
claude mcp add postgres \
  npx @modelcontextprotocol/server-postgres \
  --url postgres://localhost:5432/dev

# Linear cho task management
claude mcp add linear npx @linear-ai/mcp

# Sentry cho error tracking
claude mcp add sentry npx @sentry/mcp-server

Use case 1: Debug production issue từ Sentry alert

Claude orchestrate:

Use case 2: E2E test từ user report

  • [Sentry MCP] Fetch errors
  • [Postgres MCP] Query user data
  • [Linear MCP] Create ticket
Check Sentry cho error "UndefinedInvariantError" last 24h. 
Xem transaction ID, user affected, stack trace. Rồi check 
Postgres: user đó có data bất thường gì không? Generate 
Linear ticket với root cause hypothesis.

Use case 2: E2E test từ user report

Claude:

Kết quả

Dev productivity lên rõ: task cần cross multiple tools xưa tốn 30-60 phút → giờ 5-10 phút. Claude orchestrate giữa MCP servers, dev chỉ review.

  • [Linear MCP] Read issue
  • [Playwright MCP] Navigate, interact, screenshot
  • Report với visual proof
User nói flow checkout bị broken trong issue Linear #LN-234. 
Đọc issue detail. Reproduce bằng Playwright trên staging. 
Screenshot step fail. Report back.

Case studies theo ngành

🏥 Health tech — MCP EHR

Tình huống: Đội dev tích hợp EHR (electronic health record) vendor. Test integration tốn tuần.

Với MCP EHR custom:

💰 Finance — MCP Bloomberg terminal

Tình huống: Quant dev cần query market data real-time cho backtest.

Với Bloomberg MCP (internal):

🏭 Manufacturing — MCP MES

Tình huống: Platform team kết nối MES (manufacturing execution) với AI.

Với MES MCP:

🎓 EdTech — MCP LMS

Tình huống: Build tutor AI cho students, cần truy LMS data.

Với LMS MCP:

🛡️ Security — MCP Panther SIEM

Tình huống: SOC analyst triage alerts chậm.

Với Panther MCP:

  • Claude query FHIR patient records từ test sandbox
  • Verify mapping đúng từ EHR schema sang internal
  • Kết quả: Integration testing từ 2 tuần xuống 3 ngày.
  • Claude fetch historical prices, news
  • Run backtest logic
  • Kết quả: Research cycle từ 1 ngày xuống 2 tiếng.
  • Claude pull line KPI real-time
  • Detect anomaly, suggest root cause
  • Kết quả: Downtime giảm 15%, detect faster 4x.
  • Claude thấy student progress
  • Suggest exercise phù hợp
  • Kết quả: Personalization accurate hơn, engagement +40%.
  • Claude pull alert detail, cross-ref with threat intel
  • Suggest priority + response action
  • Kết quả: Time-to-triage 15 phút → 3 phút.

Anti-patterns

❌ Cài MCP server random chưa verify

Biểu hiện: thấy MCP server cool trên GitHub → claude mcp add xxx ngay.

Rủi ro: MCP server chạy code trên máy bạn. Nếu untrusted → có thể malicious.

Cách đúng: Chỉ cài MCP từ:

❌ Allow * MCP tool

Biểu hiện:

Rủi ro: Mọi MCP tool được gọi tự động. Nếu MCP có destructive op (delete DB, send email) → Claude có thể làm mà không hỏi.

Cách đúng: Allow cụ thể tool name, deny destructive ops:

  • Anthropic official
  • Vendor chính thức (Linear, Slack, etc.)
  • Open source có nhiều star + audit
  • Internal của công ty bạn
"allow": ["mcp__*"]

❌ Allow * MCP tool

❌ Dùng MCP cho task CLI tool làm được

Biểu hiện: Cài Git MCP dù git CLI đã có.

Hậu quả: Duplicate, thêm complexity, Claude đôi khi chọn sai tool.

Cách đúng: Ưu tiên CLI tool cho common operation.

❌ MCP server dev-only mà dùng production

Biểu hiện: Playwright MCP trong prod CI.

Rủi ro: Browser automation trong prod → side effects, data leak.

Cách đúng: MCP server có context (local dev, staging, test). Không mixing.

❌ Không restart sau khi cài/config MCP

Biểu hiện: vừa claude mcp add, mong dùng ngay.

Cách đúng: Restart Claude Code để load config mới.

"allow": ["mcp__postgres__query", "mcp__github__list_issues"],
"deny": ["mcp__postgres__execute_ddl", "mcp__github__delete_repo"]

Mẹo nâng cao

Mẹo 1: Scope MCP theo project

Config ở .claude/settings.json project-level:

Commit vào Git → team có cùng MCP khi mở project.

Mẹo 2: MCP custom cho team

Viết MCP server riêng cho internal API. Template: modelcontextprotocol.io/quickstart/server. 30 phút setup, lợi ích lâu dài.

Example: MCP acme-internal cung cấp tool get_employee_info, get_deployment_status, trigger_staging_rebuild.

Mẹo 3: Monitor MCP usage

Claude Code log mọi MCP call. Check ~/.claude/logs/ để xem tool nào gọi nhiều. Nếu thấy MCP tool dùng ít → cân nhắc uninstall, giảm clutter.

Mẹo 4: MCP với headless Claude Code (SDK)

Sẽ học ở Bài 4.18. MCP server có thể attach vào SDK run → dùng trong CI/CD, automation.

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    }
  }
}

Áp dụng ngay

Bài tập 1: Cài Playwright MCP (15 phút)

Bước 1: Cài:

Bước 2: Verify: /mcp trong Claude Code.

Bước 3: Cấu hình permission allow mcp__playwright trong .claude/settings.local.json.

Bước 4: Restart Claude Code.

Bước 5: Thử command đơn giản:

claude mcp add playwright npx @playwright/mcp@latest

Bài tập 1: Cài Playwright MCP (15 phút)

Ghi:

Bài tập 2 (optional, 20 phút): UI self-review

Chạy app uigen local (npm run dev). Prompt Claude:

  • Tool MCP nào được gọi: ____________
  • Screenshot có thành công? ☐ Có ☐ Không
Navigate to https://example.com và screenshot cho tôi. Describe 
nội dung trang.

Bài tập 2 (optional, 20 phút): UI self-review

Ghi:

  • Generation trước: style gì? __________
  • Generation sau: khác thế nào? __________
  • Prompt template thay đổi: ____________
Mở localhost:3000, generate một Button component đẹp. Screenshot, 
rồi đưa feedback về design. Dựa trên feedback đó, update 
@src/lib/prompts/generation.tsx để encourage style bạn muốn. 
Test lại với generation mới.

Tóm tắt bài học

🎯 MCP = giao thức mở — AI tool nào cũng kết nối được servers, không cần integration từng đôi.

🎯 claude mcp add — cài một MCP server trong 1 command.

🎯 Permission là phải — allow cụ thể tool, deny destructive op.

🎯 CLI tool > MCP khi có CLI phổ biến (git, docker, gh, psql).

🎯 MCP mở ra self-improving loop — Claude observe output của mình qua MCP, cải thiện.

Tài liệu tham khảo
  • MCP specification
  • MCP servers catalog
  • Build your own MCP server — tutorial
  • MCP 201 talk — Code w/ Claude 2025
  • Bài 4.2 — Coding assistant + tool use basics
  • Bài 4.18 — Claude Code SDK (dùng MCP programmatic)
Nội dung này có hữu ích không?