Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K

    第一步

    Claude 介紹快速入門

    模型與定價

    模型概覽選擇模型Claude 4.5 的新功能遷移到 Claude 4.5模型棄用定價

    使用 Claude 建構

    功能概覽使用 Messages API上下文視窗提示詞最佳實踐

    功能

    提示詞快取上下文編輯延伸思考串流訊息批次處理引用多語言支援Token 計數嵌入向量視覺PDF 支援Files API搜尋結果Google Sheets 附加元件

    工具

    概述如何實現工具使用代幣高效工具使用細粒度工具串流Bash 工具代碼執行工具電腦使用工具文字編輯工具網頁擷取工具網路搜尋工具記憶工具

    代理技能

    概述在 API 中開始使用 Agent Skills技能編寫最佳實踐使用 Agent Skills 與 API

    Agent SDK

    概述Agent SDK 參考 - TypeScriptPython SDK

    指南

    串流輸入處理權限會話管理託管 Agent SDK修改系統提示SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的代理技能追蹤成本和使用量待辦事項清單SDK 中的外掛程式

    API 中的 MCP

    MCP 連接器遠端 MCP 伺服器

    Claude 在第三方平台上

    Amazon BedrockVertex AI

    提示工程

    概述提示詞生成器使用提示模板提示詞改進器保持清晰和直接使用範例(多樣提示)讓 Claude 思考(思維鏈)使用 XML 標籤給 Claude 分配角色(系統提示詞)預填 Claude 的回應串接複雜提示長文本技巧延伸思考技巧

    測試與評估

    定義成功標準開發測試案例使用評估工具降低延遲

    加強防護措施

    減少幻覺提高輸出一致性防範越獄handle-streaming-refusals減少提示詞洩漏保持 Claude 的角色特性

    管理和監控

    Admin API 概述使用量和成本 APIClaude Code 分析 API
    Console
    指南

    自訂工具

    建立並整合自訂工具以擴展 Claude Agent SDK 功能

    自訂工具允許您透過程序內 MCP 伺服器使用自己的功能來擴展 Claude Code 的能力,讓 Claude 能夠與外部服務、API 互動,或執行專門的操作。

    建立自訂工具

    使用 createSdkMcpServer 和 tool 輔助函數來定義型別安全的自訂工具:

    TypeScript
    import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
    import { z } from "zod";
    
    // 建立一個帶有自訂工具的 SDK MCP 伺服器
    const customServer = createSdkMcpServer({
      name: "my-custom-tools",
      version: "1.0.0",
      tools: [
        tool(
          "get_weather",
          "使用座標取得某個位置的當前溫度",
          {
            latitude: z.number().describe("緯度座標"),
            longitude: z.number().describe("經度座標")
          },
          async (args) => {
            const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}&current=temperature_2m&temperature_unit=fahrenheit`);
            const data = await response.json();
    
            return {
              content: [{
                type: "text",
                text: `溫度:${data.current.temperature_2m}°F`
              }]
            };
          }
        )
      ]
    });
    Python
    from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeSDKClient, ClaudeAgentOptions
    from typing import Any
    import aiohttp
    
    # 使用 @tool 裝飾器定義自訂工具
    @tool("get_weather", "使用座標取得某個位置的當前溫度", {"latitude": float, "longitude": float})
    async def get_weather(args: dict[str, Any]) -> dict[str, Any]:
        # 呼叫天氣 API
        async with aiohttp.ClientSession() as session:
            async with session.get(
                f"https://api.open-meteo.com/v1/forecast?latitude={args['latitude']}&longitude={args['longitude']}&current=temperature_2m&temperature_unit=fahrenheit"
            ) as response:
                data = await response.json()
    
        return {
            "content": [{
                "type": "text",
                "text": f"溫度:{data['current']['temperature_2m']}°F"
            }]
        }
    
    # 使用自訂工具建立 SDK MCP 伺服器
    custom_server = create_sdk_mcp_server(
        name="my-custom-tools",
        version="1.0.0",
        tools=[get_weather]  # 傳遞裝飾過的函數
    )

    使用自訂工具

    透過 mcpServers 選項將自訂伺服器作為字典/物件傳遞給 query 函數。

    重要: 自訂 MCP 工具需要串流輸入模式。您必須為 prompt 參數使用非同步產生器/可迭代物件 - 簡單的字串無法與 MCP 伺服器一起使用。

    工具名稱格式

    當 MCP 工具暴露給 Claude 時,它們的名稱遵循特定格式:

    • 模式:mcp__{server_name}__{tool_name}
    • 範例:在伺服器 my-custom-tools 中名為 get_weather 的工具會變成 mcp__my-custom-tools__get_weather

    設定允許的工具

    您可以透過 allowedTools 選項控制 Claude 可以使用哪些工具:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 在查詢中使用自訂工具與串流輸入
    async function* generateMessages() {
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: "舊金山的天氣如何?"
        }
      };
    }
    
    for await (const message of query({
      prompt: generateMessages(),  // 使用非同步產生器進行串流輸入
      options: {
        mcpServers: {
          "my-custom-tools": customServer  // 作為物件/字典傳遞,而非陣列
        },
        // 可選擇性地指定 Claude 可以使用哪些工具
        allowedTools: [
          "mcp__my-custom-tools__get_weather",  // 允許天氣工具
          // 根據需要新增其他工具
        ],
        maxTurns: 3
      }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }

    多工具範例

    當您的 MCP 伺服器有多個工具時,您可以選擇性地允許它們:

    const multiToolServer = createSdkMcpServer({
      name: "utilities",
      version: "1.0.0",
      tools: [
        tool("calculate", "執行計算", { /* ... */ }, async (args) => { /* ... */ }),
        tool("translate", "翻譯文字", { /* ... */ }, async (args) => { /* ... */ }),
        tool("search_web", "搜尋網路", { /* ... */ }, async (args) => { /* ... */ })
      ]
    });
    
    // 只允許特定工具與串流輸入
    async function* generateMessages() {
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: "計算 5 + 3 並將 'hello' 翻譯成西班牙文"
        }
      };
    }
    
    for await (const message of query({
      prompt: generateMessages(),  // 使用非同步產生器進行串流輸入
      options: {
        mcpServers: {
          utilities: multiToolServer
        },
        allowedTools: [
          "mcp__utilities__calculate",   // 允許計算器
          "mcp__utilities__translate",   // 允許翻譯器
          // "mcp__utilities__search_web" 不被允許
        ]
      }
    })) {
      // 處理訊息
    }

    Python 的型別安全

    @tool 裝飾器支援各種模式定義方法以實現型別安全:

    import { z } from "zod";
    
    tool(
      "process_data",
      "使用型別安全處理結構化資料",
      {
        // Zod 模式定義執行時驗證和 TypeScript 型別
        data: z.object({
          name: z.string(),
          age: z.number().min(0).max(150),
          email: z.string().email(),
          preferences: z.array(z.string()).optional()
        }),
        format: z.enum(["json", "csv", "xml"]).default("json")
      },
      async (args) => {
        // args 根據模式完全型別化
        // TypeScript 知道:args.data.name 是字串,args.data.age 是數字等
        console.log(`正在將 ${args.data.name} 的資料處理為 ${args.format}`);
        
        // 您的處理邏輯在此
        return {
          content: [{
            type: "text",
            text: `已處理 ${args.data.name} 的資料`
          }]
        };
      }
    )

    錯誤處理

    優雅地處理錯誤以提供有意義的回饋:

    tool(
      "fetch_data",
      "從 API 取得資料",
      {
        endpoint: z.string().url().describe("API 端點 URL")
      },
      async (args) => {
        try {
          const response = await fetch(args.endpoint);
          
          if (!response.ok) {
            return {
              content: [{
                type: "text",
                text: `API 錯誤:${response.status} ${response.statusText}`
              }]
            };
          }
          
          const data = await response.json();
          return {
            content: [{
              type: "text",
              text: JSON.stringify(data, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `取得資料失敗:${error.message}`
            }]
          };
        }
      }
    )

    範例工具

    資料庫查詢工具

    const databaseServer = createSdkMcpServer({
      name: "database-tools",
      version: "1.0.0",
      tools: [
        tool(
          "query_database",
          "執行資料庫查詢",
          {
            query: z.string().describe("要執行的 SQL 查詢"),
            params: z.array(z.any()).optional().describe("查詢參數")
          },
          async (args) => {
            const results = await db.query(args.query, args.params || []);
            return {
              content: [{
                type: "text",
                text: `找到 ${results.length} 行:\n${JSON.stringify(results, null, 2)}`
              }]
            };
          }
        )
      ]
    });

    API 閘道工具

    const apiGatewayServer = createSdkMcpServer({
      name: "api-gateway",
      version: "1.0.0",
      tools: [
        tool(
          "api_request",
          "對外部服務進行已驗證的 API 請求",
          {
            service: z.enum(["stripe", "github", "openai", "slack"]).describe("要呼叫的服務"),
            endpoint: z.string().describe("API 端點路徑"),
            method: z.enum(["GET", "POST", "PUT", "DELETE"]).describe("HTTP 方法"),
            body: z.record(z.any()).optional().describe("請求主體"),
            query: z.record(z.string()).optional().describe("查詢參數")
          },
          async (args) => {
            const config = {
              stripe: { baseUrl: "https://api.stripe.com/v1", key: process.env.STRIPE_KEY },
              github: { baseUrl: "https://api.github.com", key: process.env.GITHUB_TOKEN },
              openai: { baseUrl: "https://api.openai.com/v1", key: process.env.OPENAI_KEY },
              slack: { baseUrl: "https://slack.com/api", key: process.env.SLACK_TOKEN }
            };
            
            const { baseUrl, key } = config[args.service];
            const url = new URL(`${baseUrl}${args.endpoint}`);
            
            if (args.query) {
              Object.entries(args.query).forEach(([k, v]) => url.searchParams.set(k, v));
            }
            
            const response = await fetch(url, {
              method: args.method,
              headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
              body: args.body ? JSON.stringify(args.body) : undefined
            });
            
            const data = await response.json();
            return {
              content: [{
                type: "text",
                text: JSON.stringify(data, null, 2)
              }]
            };
          }
        )
      ]
    });

    計算器工具

    const calculatorServer = createSdkMcpServer({
      name: "calculator",
      version: "1.0.0",
      tools: [
        tool(
          "calculate",
          "執行數學計算",
          {
            expression: z.string().describe("要評估的數學表達式"),
            precision: z.number().optional().default(2).describe("小數精度")
          },
          async (args) => {
            try {
              // 在生產環境中使用安全的數學評估庫
              const result = eval(args.expression); // 僅供範例!
              const formatted = Number(result).toFixed(args.precision);
              
              return {
                content: [{
                  type: "text",
                  text: `${args.expression} = ${formatted}`
                }]
              };
            } catch (error) {
              return {
                content: [{
                  type: "text",
                  text: `錯誤:無效表達式 - ${error.message}`
                }]
              };
            }
          }
        ),
        tool(
          "compound_interest",
          "計算投資的複利",
          {
            principal: z.number().positive().describe("初始投資金額"),
            rate: z.number().describe("年利率(以小數表示,例如 0.05 表示 5%)"),
            time: z.number().positive().describe("投資期間(年)"),
            n: z.number().positive().default(12).describe("每年複利頻率")
          },
          async (args) => {
            const amount = args.principal * Math.pow(1 + args.rate / args.n, args.n * args.time);
            const interest = amount - args.principal;
            
            return {
              content: [{
                type: "text",
                text: `投資分析:\n` +
                      `本金:$${args.principal.toFixed(2)}\n` +
                      `利率:${(args.rate * 100).toFixed(2)}%\n` +
                      `時間:${args.time} 年\n` +
                      `複利:每年 ${args.n} 次\n\n` +
                      `最終金額:$${amount.toFixed(2)}\n` +
                      `賺取利息:$${interest.toFixed(2)}\n` +
                      `回報:${((interest / args.principal) * 100).toFixed(2)}%`
              }]
            };
          }
        )
      ]
    });

    相關文件

    • TypeScript SDK 參考
    • Python SDK 參考
    • MCP 文件
    • SDK 概述
    • Python 的型別安全
    • API 閘道工具
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC