# Claude Desktop 與 MCP 完整使用指南 :::info **文章更新時間:** 2025年5月 **適用版本:** Claude Desktop 最新版本 **作者:** AI 開發實踐指南 ::: ## 🚀 前言 Claude Desktop 配合 MCP (Model Context Protocol) 為 AI 輔助開發帶來革命性的體驗。本指南將深入介紹如何充分利用 Claude Desktop 的強大功能,包括 CLI 工具、MCP 服務整合、以及各種高效的使用技巧。 ## 📋 目錄 [TOC] --- ## 1. Claude Desktop 基礎設置 ### 1.1 安裝 Claude Desktop :::warning **重要提醒** Claude Desktop 目前僅支援 macOS 和 Windows,尚不支援 Linux。 ::: 1. **下載安裝程式** - 訪問 [Claude 官方網站](https://claude.ai/download) - 選擇適合您作業系統的版本下載 - 按照安裝指示完成安裝 2. **檢查更新** ```bash # 在 Claude 選單中選擇「檢查更新...」 # 或使用快捷鍵檢查版本 ``` ### 1.2 基本配置 建立基本的工作環境: ```bash # 建立 Claude 設定目錄 mkdir -p ~/.claude/commands mkdir -p ~/.claude/config ``` ## 2. Claude Code 作為 CLI 工具 ### 2.1 命令列參數 Claude Code 提供強大的 CLI 功能,支援多種操作模式: ```bash # 基本啟動 claude # 無頭模式運行 claude -p # 傳遞參數啟動 claude --project /path/to/project # 管道操作 echo "分析這個程式碼" | claude # 同時運行多個實例 claude & claude --instance=2 & ``` ### 2.2 核心功能特性 - ✅ **多實例支援**:可同時運行多個 Claude 實例 - ✅ **管道整合**:與其他命令列工具無縫鏈接 - ✅ **子代理啟動**:Claude 可以啟動自己的實例處理子任務 - ✅ **headless 模式**:適合自動化腳本使用 ## 3. 圖像處理功能 ### 3.1 圖像輸入方式 **拖曳圖片(macOS)** ```bash # 直接將圖片檔案拖曳到終端機視窗中 # 支援格式:PNG, JPG, GIF, WebP ``` **截圖與貼上** ```bash # 1. 使用 macOS 截圖快捷鍵 Shift + Command + Control + 4 # 複製螢幕截圖到剪貼板 # 2. 在 Claude Code 中貼上 Control + V # 注意:是 Control + V,不是 Command + V ``` ### 3.2 實際應用場景 **設計 Mockup 開發** ```markdown 1. 設計師提供 UI mockup 2. 將 mockup 截圖貼入 Claude 3. 要求 Claude 根據設計構建前端介面 4. 實現閉環開發流程 ``` **自動化視覺測試** ```bash # 使用 Puppeteer MCP server 自動截圖 /mcp puppeteer screenshot --url="http://localhost:3000" # Claude 會自動分析截圖並提供改進建議 ``` ## 4. MCP 服務深度整合 ### 4.1 什麼是 MCP? :::info **MCP (Model Context Protocol)** 是一種開放協議,標準化了應用程式向 LLM 提供上下文的方式。就像 USB-C 為設備提供標準化連接一樣,MCP 為 AI 模型與不同數據源和工具之間提供標準化連接。 ::: ### 4.2 MCP 設定檔配置 在 `~/.claude/config.json` 中添加 MCP 服務器: ```json { "mcpServers": { "filesystem": { "command": "npx", "args": ["@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] }, "postgres": { "command": "npx", "args": ["@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/db"] }, "github": { "command": "npx", "args": ["@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "your_token_here" } } } } ``` ### 4.3 常用 MCP 命令 **檔案系統操作** ```bash /mcp filesystem list /path/to/directory /mcp filesystem read /path/to/file.txt /mcp filesystem write /path/to/new-file.txt "content" /mcp filesystem search "search_term" /path/to/search ``` **資料庫操作** ```bash /mcp postgres query "SELECT * FROM users LIMIT 10" /mcp postgres schema users /mcp postgres explain "SELECT * FROM complex_query" ``` **GitHub 整合** ```bash /mcp github repos list /mcp github issues list --repo owner/repo /mcp github pr create --title "Feature" --body "Description" /mcp github review --pr 123 --comment "LGTM" ``` ### 4.4 熱門 MCP 伺服器 | 伺服器類型 | 功能描述 | 安裝命令 | |-----------|---------|----------| | **Filesystem** | 檔案系統操作 | `npm install @modelcontextprotocol/server-filesystem` | | **PostgreSQL** | 資料庫查詢與管理 | `npm install @modelcontextprotocol/server-postgres` | | **GitHub** | Git 操作與程式碼審查 | `npm install @modelcontextprotocol/server-github` | | **Puppeteer** | 網頁自動化與截圖 | `npm install @modelcontextprotocol/server-puppeteer` | | **Slack** | 團隊通訊整合 | `npm install @modelcontextprotocol/server-slack` | | **Brave Search** | 網路搜尋功能 | `npm install @modelcontextprotocol/server-brave-search` | ## 5. claude.md 專案配置 ### 5.1 claude.md 文件概述 `claude.md` 是 Claude Desktop 的核心配置文件,每次向 Claude 發出請求時都會載入。它充當專案的上下文提示,包含專案特定的指引和設定。 ### 5.2 claude.md 內容結構 **基本專案資訊** ```markdown # 專案名稱:我的 Web 應用程式 ## 技術棧 - Frontend: React + TypeScript - Backend: Node.js + Express - Database: PostgreSQL - Styling: Tailwind CSS ## 常用指令 bash npm run dev # 啟動開發伺服器 npm run build # 建構生產版本 npm test # 執行測試 npm run lint # 程式碼檢查 ## 程式碼風格 - 使用 TypeScript 嚴格模式 - 遵循 ESLint 規則 - 使用 Prettier 格式化 - 採用函數式組件和 Hooks ## 測試指引 - 所有新功能都需要測試覆蓋 - 使用 Jest + React Testing Library - 最小測試覆蓋率:80% ## Git 工作流程 - 使用 feature 分支開發 - PR 需要通過 CI/CD 檢查 - 需要 code review 才能合併 ``` ### 5.3 claude.md 管理命令 **初始化專案配置** ```bash /init # 掃描目錄並自動生成 claude.md ``` **添加專案指引** ```bash # 在程式碼中添加指令到 claude.md # 範例:在檔案中加入註解 # claude.md: 此模組負責用戶認證,請確保遵循安全最佳實踐 ``` ### 5.4 多層級 claude.md 配置 **全域設定(~/.claude/claude.md)** ```markdown # 全域 Claude 設定 ## 個人偏好 - 偏好使用 TypeScript - 喜歡函數式程式設計風格 - 重視程式碼可讀性和維護性 ## 常用工具 - Git 工作流程偏好 - 編輯器:VS Code - 終端:iTerm2 + zsh ``` **專案特定設定(./claude.md)** ```markdown # 當前專案設定 ## 專案特殊需求 - 特定的 API 規格 - 專案特有的架構模式 - 團隊協作規範 ``` **子目錄設定(./src/components/claude.md)** ```markdown # 元件開發指引 ## React 元件規範 - 使用 TypeScript 介面定義 props - 實作 error boundary - 加入適當的 accessibility 屬性 ``` ## 6. 斜線命令系統 ### 6.1 內建斜線命令 Claude Desktop 提供豐富的內建命令,方便使用者在互動式會話中控制 Claude 的行為: | 命令 | 功能描述 | 使用範例與說明 | |------|---------|----------| | `/help` | 顯示所有可用命令 | `/help` - 列出所有斜線命令及其簡要說明。 | | `/init` | 初始化專案設定 | `/init` - 掃描目前目錄結構,並產生一個基礎的 `claude.md` 檔案,作為專案的初始指引。 | | `/clear` | 清除對話歷史 | `/clear` - 清除目前的對話記錄,重新開始一個乾淨的會話。 | | `/compact [instructions]` | 壓縮上下文 | `/compact` - 壓縮目前的對話歷史以節省 token。可選參數 `[instructions]` 用於指導壓縮過程,例如 `/compact "保留最近的程式碼變更"`。 | | `/config` | 檢視/修改設定 | `/config` - 進入設定模式,可以檢視或修改 Claude Code 的設定,例如主題、API 金鑰等。 | | `/cost` | 顯示 token 使用統計 | `/cost` - 顯示目前會話或專案的 token 使用量統計,幫助使用者追蹤成本。 | | `/doctor` | 檢查 Claude Code 安裝狀態 | `/doctor` - 執行一系列檢查,確認 Claude Code 的安裝是否完整且運作正常。 | | `/login` | 切換 Anthropic 帳戶 | `/login` - 允許使用者登入或切換不同的 Anthropic 帳戶。 | | `/logout` | 登出 Anthropic 帳戶 | `/logout` - 登出目前使用的 Anthropic 帳戶。 | | `/memory` | 編輯 claude.md 記憶檔案 | `/memory` - 開啟 `claude.md` 檔案進行編輯,方便快速修改專案指引。 | | `/pr_comments` | 檢視 Pull Request 評論 | `/pr_comments` - (需整合 GitHub MCP) 檢視指定 Pull Request 的評論。 | | `/review` | 請求程式碼審查 | `/review` - (需整合 GitHub MCP) 請求 Claude 對指定的程式碼檔案或 Pull Request 進行審查。 | | `/status` | 檢視帳戶與系統狀態 | `/status` - 顯示目前帳戶資訊、系統狀態以及 MCP 伺服器連線狀態。 | | `/terminal-setup` | 設定終端機換行快速鍵 | `/terminal-setup` - 自動為 iTerm2 和 VSCode 終端機設定 Shift+Enter 作為換行鍵。 | | `/vim` | 進入 Vim 模式 | `/vim` - 切換到 Vim 輸入模式,可以使用 Vim 的部分快捷鍵進行編輯。 | | `/bug` | 回報錯誤 | `/bug` - 將目前的對話內容(包含錯誤訊息)傳送給 Anthropic 團隊以協助改善產品。 | | `/mcp` | MCP 服務操作 | `/mcp <server_name> <command> [args]` - 與已設定的 MCP 伺服器互動,例如 `/mcp filesystem list .`。 | | `/commit` | Git 提交操作 | `/commit "feat: add new login feature"` - (需整合 Git) 執行 Git 提交。也支援 `--generate-message` 自動產生提交訊息。 | | `/test` | 執行測試 | `/test --file src/utils.test.js` - (需專案配置) 執行專案中定義的測試。 | | `/lint` | 程式碼檢查 | `/lint src/components/` - (需專案配置) 對指定路徑的程式碼執行 Linting。 | | `/refactor` | 程式碼重構 | `/refactor --strategy=performance src/heavy_logic.js` - (需專案配置) 請求 Claude 協助重構程式碼。 | **特殊快捷鍵:** - **`#` 快速記憶**: 在輸入的開頭使用 `#` 可以快速將該行內容儲存到記憶檔案 (`claude.md` 或其他指定檔案) 中。系統會提示選擇要儲存的記憶檔案。 ```bash # 這是一個重要的專案筆記,需要記住 ``` - **終端機換行**: - **Option + Enter** (macOS Terminal.app, iTerm2, VSCode): 預設的換行方式。 - **Shift + Enter** (iTerm2, VSCode): 透過 `/terminal-setup` 命令設定後,可使用此更直觀的快捷鍵。 ### 6.2 自訂斜線命令 在 `~/.claude/commands/` 目錄中建立自訂命令: **GitHub Issue 處理命令** ```markdown <!-- ~/.claude/commands/github-issue.md --> # GitHub Issue 處理 分析並修復以下 GitHub issue: Issue #{{1}} 請: 1. 理解問題描述 2. 分析相關程式碼 3. 提供修復方案 4. 撰寫測試案例 5. 準備 PR 說明 ``` **程式碼審查命令** ```markdown <!-- ~/.claude/commands/code-review.md --> # 程式碼審查 請對以下程式碼進行全面審查: 檔案:{{1}} 審查重點: - 程式碼品質 - 效能考量 - 安全性問題 - 最佳實踐遵循 - 測試覆蓋率 請提供具體的改進建議。 ``` ### 6.3 命令使用範例 ```bash # 使用自訂命令處理 GitHub issue /github-issue 123 # 程式碼審查 /code-review src/components/UserProfile.tsx # 重構優化 /refactor src/utils/dataProcessor.js ``` ## 7. 使用者介面技巧 ### 7.1 鍵盤快捷鍵 | 快捷鍵 | 功能 | 說明 | |--------|------|------| | `Tab` | 自動補全 | 檔案路徑和命令補全 | | `Escape` | 中斷操作 | 立即停止 Claude 的當前任務 | | `Ctrl+C` | 複製 | 複製選取內容 | | `Ctrl+V` | 貼上圖片 | 貼上剪貼板中的圖片 | | `Cmd+K` | 快速命令 | 開啟命令選單 | | `Cmd+,` | 設定 | 開啟設定介面 | ### 7.2 智慧提示技巧 **使用 Tab 補全提升精準度** ```bash # 不精確的指令 "分析這個檔案" # 使用 Tab 補全的精確指令 "分析 src/components/UserProfile.tsx 檔案的效能問題" ``` **善用 Escape 鍵控制對話方向** ```bash # 當 Claude 偏離預期時 按 Escape → "請撤銷上一步,改為專注於錯誤處理部分" ``` ## 8. 版本控制整合 ### 8.1 Git 工作流程最佳實踐 **頻繁提交策略** ```bash # 完成功能後立即提交 git add . git commit -m "feat: 新增用戶登入功能" # 讓 Claude 撰寫提交訊息 /commit --generate-message ``` **智慧提交訊息** ```bash # Claude 會分析變更內容並生成語意化提交訊息 /commit --analyze-changes # 輸出範例: # "feat(auth): implement JWT-based authentication with refresh tokens # # - Add JWT token generation and validation # - Implement refresh token rotation # - Add middleware for protected routes # - Include comprehensive error handling" ``` ### 8.2 回溯與重新開始策略 **戰略性回溯** ```bash # 檢查最近的提交 git log --oneline -10 # 回溯到穩定狀態 git reset --hard HEAD~3 # 清除 Claude 對話歷史並重新開始 /clear "從最後一個穩定的提交重新開始,請實現 XYZ 功能" ``` ## 9. GitHub 深度整合 ### 9.1 GitHub CLI 設定 **安裝與認證** ```bash # 安裝 GitHub CLI brew install gh # 認證 gh auth login # 設定預設編輯器 gh config set editor code ``` ### 9.2 GitHub MCP 伺服器功能 **專案管理** ```bash /mcp github repos create my-new-project --private /mcp github repos clone owner/repo /mcp github repos fork owner/repo ``` **Issue 管理** ```bash /mcp github issues create --title "Bug 修復" --body "詳細描述..." /mcp github issues list --state open --assignee @me /mcp github issues close 123 --comment "已修復" ``` **Pull Request 工作流程** ```bash # 建立 PR /mcp github pr create --title "新功能:用戶認證" \ --body "詳細 PR 描述" \ --draft # 程式碼審查 /mcp github pr review 456 --approve --comment "LGTM!" # 合併 PR /mcp github pr merge 456 --squash ``` ### 9.3 自動化 GitHub 工作流程 **CI/CD 整合** ```yaml # .github/workflows/claude-review.yml name: Claude Code Review on: pull_request: types: [opened, synchronize] jobs: claude-review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Claude Code Review run: | claude /code-review ${{ github.event.pull_request.head.sha }} ``` ## 10. 上下文管理與成本優化 ### 10.1 Token 使用監控 **即時監控** ```bash # 檢查當前 token 使用量 /tokens status # 詳細使用統計 /tokens usage --detailed # 設定使用限制警告 /tokens limit --warning-at 80% --stop-at 95% ``` ### 10.2 上下文壓縮策略 **智慧壓縮時機** ```bash # 任務完成後壓縮 "任務完成,請壓縮上下文準備下一個任務" /compress --preserve-key-context # 自動壓縮設定 /settings auto-compress --at 90% --preserve recent-commits ``` **外部記憶替代方案** ```bash # 使用 GitHub Issues 作為外部記憶 /mcp github issues create --title "專案計畫" \ --body "$(echo '目前進度和下一步計畫')" # 使用 Scratchpads /scratchpad create project-plan /scratchpad save current-status "目前實作狀態:..." ``` ### 10.3 Open Telemetry 整合 **設定追蹤** ```json { "telemetry": { "endpoint": "https://api.datadoghq.com/v1/traces", "service": "claude-development", "environment": "production", "tags": { "team": "frontend", "project": "user-dashboard" } } } ``` **成本分析** ```bash # 團隊使用量報告 /telemetry report --team frontend --period month # 專案成本分析 /telemetry costs --project user-dashboard --breakdown ``` ## 11. 進階使用技巧 ### 11.1 多專案管理 **專案切換** ```bash # 切換專案上下文 claude --project ~/projects/web-app claude --project ~/projects/mobile-app # 同時管理多專案 claude --instance web & claude --instance mobile & ``` ### 11.2 團隊協作最佳實踐 **共享設定** ```bash # 建立團隊 claude.md 模板 mkdir -p team-templates/ cp claude.md team-templates/frontend-template.md # 同步團隊設定 git clone team-claude-configs ln -s team-claude-configs/frontend.md ./claude.md ``` ### 11.3 自動化腳本整合 **部署腳本** ```bash #!/bin/bash # deploy.sh echo "開始部署流程..." | claude --context deployment # 執行測試 npm test # 建構應用程式 npm run build # 部署到 staging echo "部署到 staging 環境" | claude --log-deployment # Claude 輔助驗證 claude "請驗證 staging 環境的部署狀態" ``` ## 12. 疑難排解 ### 12.1 常見問題 **MCP 連接問題** ```bash # 檢查 MCP 服務狀態 /mcp status # 重啟 MCP 服務 /mcp restart filesystem # 檢查配置 /mcp config validate ``` **效能優化** ```bash # 清理快取 /cache clear # 重置設定 /settings reset --keep-auth # 檢查記憶體使用 /system status ``` ### 12.2 偵錯模式 **啟用詳細日志** ```bash claude --debug --log-level verbose # 查看日志 tail -f ~/.claude/logs/debug.log ``` ## 13. 方案升級建議 ### 13.1 Claude Max 方案優勢 :::success **建議升級到 Claude Max 方案的理由:** - 🚀 **更高的 token 限制**:適合大型專案開發 - ⚡ **優先處理速度**:減少等待時間 - 🔧 **進階功能存取**:包含最新的 MCP 功能 - 📊 **詳細使用分析**:更好的成本控制 - 👥 **團隊協作工具**:多人開發支援 ::: ### 13.2 成本效益分析 | 方案 | 月費 | 適用場景 | 建議用戶 | |------|------|---------|----------| | **免費版** | $0 | 個人學習、小專案 | 初學者 | | **Pro** | $20 | 專業開發、中型專案 | 獨立開發者 | | **Max** | $100+ | 大型專案、團隊開發 | 企業用戶 | ## 14. 實戰範例 ### 14.1 完整專案開發流程 **1. 專案初始化** ```bash mkdir my-react-app && cd my-react-app claude /init ``` **2. 設定 MCP 服務** ```bash /mcp filesystem enable . /mcp github connect --repo my-username/my-react-app ``` **3. 開發循環** ```bash # 開發新功能 "請建立一個用戶登入元件" # 測試 /test components/Login.test.tsx # 程式碼審查 /code-review src/components/Login.tsx # 提交 /commit --generate-message ``` **4. 部署準備** ```bash /lint --fix /test --coverage /mcp github pr create --title "Add user authentication" ``` ## 15. 總結 Claude Desktop 配合 MCP 提供了前所未有的 AI 輔助開發體驗。透過: - 🔄 **完整的 CLI 整合**:seamless 命令列操作 - 🔌 **豐富的 MCP 生態系統**:連接各種開發工具 - 📝 **智慧的專案配置**:claude.md 與斜線命令 - 🎯 **精準的上下文管理**:有效控制成本 - 🚀 **自動化工作流程**:提升開發效率 掌握這些技巧,您將能充分發揮 AI 輔助開發的威力,大幅提升程式設計效率和程式碼品質。 --- :::info **相關資源** - [Claude Desktop 官方文件](https://docs.anthropic.com/claude/desktop) - [MCP 協定規範](https://modelcontextprotocol.io/) - [Anthropic Prompt Optimizer](https://console.anthropic.com/prompt-optimizer) - [GitHub CLI 文件](https://cli.github.com/manual/) ::: **最後更新:** 2025年5月29日 **版本:** v2.0 --- ## 16. Claude Code 進階設定配置 ### 16.1 settings.json 完整配置 Claude Code 使用層次化的 `settings.json` 文件進行配置,支援全域和專案級別的設定。 **配置檔案位置優先順序:** 1. `./claude/settings.json` (專案層級) 2. `~/.claude/settings.json` (用戶層級) 3. 系統預設值 **完整 settings.json 範例:** ```json { "apiKeyHelper": "/bin/generate_temp_api_key.sh", "cleanupPeriodDays": 20, "env": { "NODE_ENV": "development", "DEBUG": "true", "API_BASE_URL": "https://api.example.com" }, "includeCoAuthoredBy": false, "mcpServers": { "filesystem": { "command": "npx", "args": ["@modelcontextprotocol/server-filesystem", "/Users/oliver/projects"] }, "postgres": { "command": "npx", "args": ["@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/mydb"] }, "github": { "command": "npx", "args": ["@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx" } }, "brave-search": { "command": "npx", "args": ["@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "BSA_xxxxxxxxxxxx" } } }, "allowedTools": [ "Bash(npm run test:*)", "Edit(src/**)", "Read(docs/**)", "WebFetch(domain:docs.anthropic.com)", "mcp__github__*" ] } ``` ### 16.2 設定管理命令 **基本設定操作:** ```bash # 查看當前配置 claude config # 設定專案配置 claude config set cleanupPeriodDays 30 # 設定全域配置 claude config set -g theme dark # 檢視特定設定值 claude config get apiKeyHelper # 移除設定 claude config unset includeCoAuthoredBy ``` **全域配置選項:** ```bash # 主題設定 claude config set -g theme dark-daltonized # 自動更新設定 claude config set -g autoUpdaterStatus disabled # 通知設定 claude config set -g preferredNotifChannel iterm2_with_bell # 詳細輸出模式 claude config set -g verbose true ``` ### 16.3 工具權限管理 **使用 `/allowed-tools` 管理權限:** ```bash # 檢視目前權限設定 /allowed-tools # 添加權限規則到 settings.json # 然後重新載入設定 ``` **常用權限規則範例:** **Bash 命令權限:** ```json { "allowedTools": [ "Bash(npm run build)", // 精確匹配 "Bash(npm run test:*)", // 前綴匹配 "Bash(git add .)", // Git 操作 "Bash(docker-compose up -d)", // Docker 命令 "Bash(yarn install)" // 套件管理 ] } ``` **檔案操作權限:** ```json { "allowedTools": [ "Read(src/**)", // 讀取 src 目錄所有檔案 "Edit(src/components/**)", // 編輯元件檔案 "Edit(~/.zshrc)", // 編輯家目錄檔案 "Read(//tmp/build_cache)", // 絕對路徑 "Edit(node_modules/**)", // 排除 node_modules "Read(docs/**/*.md)" // 特定檔案類型 ] } ``` **MCP 工具權限:** ```json { "allowedTools": [ "mcp__github__*", // 所有 GitHub MCP 工具 "mcp__postgres__query", // 特定資料庫查詢工具 "mcp__filesystem__read_file", // 檔案系統讀取 "mcp__puppeteer__puppeteer_navigate" // Puppeteer 導航工具 ] } ``` **網路存取權限:** ```json { "allowedTools": [ "WebFetch(domain:docs.anthropic.com)", // 特定網域 "WebFetch(domain:github.com)", // GitHub 存取 "WebFetch(domain:api.openai.com)" // API 存取 ] } ``` ### 16.4 環境變數完整配置 **在 settings.json 中設定環境變數:** ```json { "env": { "ANTHROPIC_MODEL": "claude-3-5-sonnet-20241022", "ANTHROPIC_SMALL_FAST_MODEL": "claude-3-haiku-20240307", "BASH_DEFAULT_TIMEOUT_MS": "300000", "BASH_MAX_TIMEOUT_MS": "600000", "BASH_MAX_OUTPUT_LENGTH": "50000", "NODE_ENV": "development", "DEBUG": "app:*", "GITHUB_TOKEN": "ghp_xxxxxxxxxxxx", "DATABASE_URL": "postgresql://user:pass@localhost/db" } } ``` **進階環境變數設定:** ```bash # API 相關設定 export ANTHROPIC_AUTH_TOKEN="your_custom_token" export ANTHROPIC_CUSTOM_HEADERS="X-Custom-Header: value" # Proxy 設定 export HTTP_PROXY="http://proxy.company.com:8080" export HTTPS_PROXY="http://proxy.company.com:8080" # 除錯與監控 export CLAUDE_CODE_USE_BEDROCK=1 export CLAUDE_CODE_USE_VERTEX=1 export DISABLE_TELEMETRY=1 export DISABLE_AUTOUPDATER=1 # MCP 相關設定 export MCP_TIMEOUT=30000 export MCP_TOOL_TIMEOUT=10000 ``` ### 16.5 API 金鑰管理 **自訂 API 金鑰助手:** ```bash #!/bin/bash # ~/.claude/scripts/api_key_helper.sh # 從環境變數獲取 if [ -n "$CLAUDE_API_KEY" ]; then echo "$CLAUDE_API_KEY" exit 0 fi # 從 AWS Secrets Manager 獲取 aws secretsmanager get-secret-value \ --secret-id "claude-api-key" \ --query SecretString \ --output text # 從 1Password 獲取 op read "op://Private/Claude API Key/credential" ``` **設定 API 金鑰助手:** ```json { "apiKeyHelper": "~/.claude/scripts/api_key_helper.sh", "env": { "CLAUDE_CODE_API_KEY_HELPER_TTL_MS": "3600000" } } ``` ### 16.6 通知與終端設定 **通知設定選項:** ```bash # iterm2 通知(推薦) claude config set -g preferredNotifChannel iterm2 # 帶聲音的 iterm2 通知 claude config set -g preferredNotifChannel iterm2_with_bell # 終端響鈴 claude config set -g preferredNotifChannel terminal_bell # 停用所有通知 claude config set -g preferredNotifChannel notifications_disabled ``` **終端優化設定:** ```bash # 在 Claude 中執行自動設定 /terminal-setup # 手動設定 Option+Enter 換行(Terminal.app) # 在終端偏好設定中: # 鍵盤 → 將 Option 鍵當作 Meta 鍵使用 # Vim 模式啟用 /vim # 或透過設定檔 claude config set -g vimMode true ``` ### 16.7 實際應用範例 **開發團隊設定範例:** ```json { "cleanupPeriodDays": 7, "includeCoAuthoredBy": true, "env": { "NODE_ENV": "development", "ESLINT_CONFIG": "company-standard", "PRETTIER_CONFIG": ".prettierrc.company" }, "allowedTools": [ "Bash(npm run *)", "Bash(yarn *)", "Bash(git *)", "Edit(src/**)", "Edit(tests/**)", "Read(docs/**)", "WebFetch(domain:company-docs.internal)", "mcp__github__*", "mcp__slack__send_message" ], "mcpServers": { "company-db": { "command": "npx", "args": ["@company/mcp-database-server"], "env": { "DB_CONNECTION": "company_dev_db" } } } } ``` **個人開發者設定範例:** ```json { "cleanupPeriodDays": 30, "includeCoAuthoredBy": false, "apiKeyHelper": "~/.claude/get_api_key.sh", "env": { "ANTHROPIC_MODEL": "claude-3-5-sonnet-20241022", "BASH_DEFAULT_TIMEOUT_MS": "180000", "DEBUG": "myapp:*" }, "allowedTools": [ "Bash(*)", "Edit(**)", "Read(**)", "WebFetch(*)", "mcp__*" ], "mcpServers": { "filesystem": { "command": "npx", "args": ["@modelcontextprotocol/server-filesystem", "/Users/username/projects"] }, "github": { "command": "npx", "args": ["@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_personal_token" } } } } ``` ### 16.8 配置疑難排解 **常見配置問題:** ```bash # 檢查配置有效性 claude config validate # 重置配置到預設值 claude config reset # 檢視完整配置來源 claude config debug # 測試 MCP 連接 /mcp status --detailed # 檢查權限問題 /allowed-tools --validate ``` **配置備份與恢復:** ```bash # 備份設定 cp ~/.claude/settings.json ~/.claude/settings.json.backup # 恢復設定 cp ~/.claude/settings.json.backup ~/.claude/settings.json # 同步團隊設定 git clone https://github.com/company/claude-configs.git ln -sf claude-configs/team-settings.json ~/.claude/settings.json ``` ## 17. 設定最佳實踐與範例 ### 17.1 不同專案類型的設定模板 **React/Next.js 專案設定:** ```json { "cleanupPeriodDays": 14, "includeCoAuthoredBy": true, "env": { "NODE_ENV": "development", "NEXT_TELEMETRY_DISABLED": "1", "FAST_REFRESH": "true" }, "allowedTools": [ "Bash(npm run dev)", "Bash(npm run build)", "Bash(npm run test:*)", "Bash(npx next:*)", "Edit(src/**)", "Edit(components/**)", "Edit(pages/**)", "Edit(app/**)", "Read(docs/**)", "WebFetch(domain:nextjs.org)", "WebFetch(domain:react.dev)" ], "mcpServers": { "filesystem": { "command": "npx", "args": ["@modelcontextprotocol/server-filesystem", "./src"] } } } ``` **Python/Django 專案設定:** ```json { "cleanupPeriodDays": 21, "env": { "PYTHONPATH": ".", "DJANGO_SETTINGS_MODULE": "myproject.settings.development", "DEBUG": "True" }, "allowedTools": [ "Bash(python manage.py *)", "Bash(pip install *)", "Bash(pytest *)", "Edit(myapp/**)", "Edit(templates/**)", "Read(requirements.txt)", "mcp__postgres__*" ], "mcpServers": { "postgres": { "command": "npx", "args": ["@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/mydb"] } } } ``` ### 17.2 安全性設定指南 **生產環境安全設定:** ```json { "cleanupPeriodDays": 3, "includeCoAuthoredBy": true, "apiKeyHelper": "/usr/local/bin/get_claude_key_from_vault.sh", "env": { "NODE_ENV": "production", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1" }, "allowedTools": [ "Read(src/**)", "Read(docs/**)", "Bash(npm run test)", "Bash(npm run lint)" ] } ``` **開發環境權限設定:** ```json { "allowedTools": [ "Bash(npm run *)", "Bash(git status)", "Bash(git add .)", "Bash(git commit *)", "Edit(src/**)", "Edit(tests/**)", "Read(**)", "WebFetch(domain:docs.*)", "mcp__github__issues_*", "mcp__github__pulls_*" ] } ``` ### 17.3 效能優化設定 **高效能設定:** ```json { "cleanupPeriodDays": 7, "env": { "BASH_DEFAULT_TIMEOUT_MS": "120000", "BASH_MAX_TIMEOUT_MS": "300000", "BASH_MAX_OUTPUT_LENGTH": "25000", "MCP_TIMEOUT": "20000", "MCP_TOOL_TIMEOUT": "8000", "DISABLE_COST_WARNINGS": "1" } } ``` ### 17.4 團隊協作設定 **共享團隊設定腳本:** ```bash #!/bin/bash # setup-team-claude.sh # 建立團隊設定目錄 mkdir -p ~/.claude/team-configs # 下載團隊設定 curl -o ~/.claude/team-configs/settings.json \ https://company.com/claude-configs/team-settings.json # 建立符號連結 ln -sf ~/.claude/team-configs/settings.json ~/.claude/settings.json # 設定團隊斜線命令 git clone https://github.com/company/claude-commands.git ~/.claude/commands echo "Team Claude configuration installed!" ``` ### 17.5 監控與日誌設定 **詳細日誌設定:** ```json { "env": { "CLAUDE_CODE_LOG_LEVEL": "debug", "CLAUDE_CODE_LOG_FILE": "~/.claude/logs/claude.log", "BASH_LOG_COMMANDS": "1" } } ``` **監控腳本範例:** ```bash #!/bin/bash # monitor-claude-usage.sh # 檢查 Claude 使用狀況 claude config get cleanupPeriodDays # 統計對話數量 find ~/.claude/chats -name "*.json" | wc -l # 檢查磁盤使用量 du -sh ~/.claude/ # 清理舊對話 find ~/.claude/chats -mtime +30 -delete ``` --- :::info **設定檔管理建議** 1. **版本控制**:將團隊設定檔加入 Git 管理 2. **環境分離**:開發、測試、生產環境使用不同設定 3. **安全性**:敏感資訊使用環境變數或外部金鑰管理 4. **備份**:定期備份個人化設定 5. **文件化**:為團隊設定撰寫清楚的說明文件 :::