Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    串流輸入即時串流回應處理停止原因處理權限使用者核准與輸入使用 hooks 控制執行工作階段管理檔案檢查點SDK 中的結構化輸出託管 Agent SDK安全部署 AI 代理修改系統提示詞SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的 Agent Skills追蹤成本與用量待辦清單SDK 中的外掛
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞產生器使用提示詞範本提示詞改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 Claude 角色(系統提示詞)串聯複雜提示詞長上下文技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    強化防護機制
    減少幻覺提高輸出一致性防範越獄攻擊串流拒絕減少提示詞洩漏讓 Claude 保持角色
    管理與監控
    Admin API 概覽資料駐留工作區用量與成本 APIClaude Code Analytics API零資料保留
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

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

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    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

    Learn

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

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

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

    自訂工具

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

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

    建立自訂工具

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

    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`
              }]
            };
          }
        )
      ]
    });

    使用自訂工具

    透過 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 概述

    Was this page helpful?

    • Python 的型別安全
    • API 閘道工具