Loading...
    • 開発者ガイド
    • API リファレンス
    • MCP
    • リソース
    • リリースノート
    Search...
    ⌘K

    はじめの一歩

    Claudeの紹介クイックスタート

    モデルと料金

    モデル概要モデルの選択Claude 4.5の新機能Claude 4.5への移行モデルの廃止予定価格設定

    Claudeで構築する

    機能概要Messages API の使用コンテキストウィンドウプロンプトのベストプラクティス

    機能

    プロンプトキャッシングコンテキスト編集拡張思考ストリーミングメッセージバッチ処理引用多言語サポートトークンカウント埋め込みビジョンPDFサポートFiles API検索結果Google Sheetsアドオン

    ツール

    概要ツール使用の実装方法トークン効率的なツール使用細粒度ツールストリーミングBashツールコード実行ツールコンピュータ使用ツールテキストエディタツールWeb fetch toolウェブ検索ツールメモリツール

    エージェントスキル

    概要クイックスタートスキル作成のベストプラクティスAPIでエージェントスキルを使用する

    Agent SDK

    概要Agent SDK リファレンス - TypeScriptPython SDK

    ガイド

    ストリーミング入力権限の処理セッション管理Agent SDKのホスティングシステムプロンプトの変更SDK内のMCPカスタムツールSDKにおけるサブエージェントSDKでのスラッシュコマンドSDK内のエージェントスキルコストと使用量の追跡Todo リストSDK のプラグイン

    API内のMCP

    MCPコネクタリモートMCPサーバー

    Claude on 3rd-party platforms

    Amazon BedrockVertex AI

    プロンプトエンジニアリング

    概要プロンプトジェネレータープロンプトテンプレートの使用プロンプト改善ツール明確で直接的な指示例(マルチショットプロンプト)を使用してClaudeの動作を導くClaudeに考えさせる(CoT)XMLタグを使用Claudeに役割を与える(システムプロンプト)Claudeの応答を事前入力複雑なプロンプトのチェーン化長文コンテキストのヒント拡張思考のヒント

    テストと評価

    成功基準を定義するテストケースを開発する評価ツールの使用レイテンシの削減

    ガードレールを強化

    幻覚を減らす出力の一貫性を高めるジェイルブレイクの軽減handle-streaming-refusalsプロンプトリークの削減Claudeのキャラクターを維持

    管理とモニタリング

    Admin API概要使用量とコストAPIClaude Code Analytics 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",
          "Get current temperature for a location using coordinates",
          {
            latitude: z.number().describe("Latitude coordinate"),
            longitude: z.number().describe("Longitude coordinate")
          },
          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: `Temperature: ${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", "Get current temperature for a location using coordinates", {"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"Temperature: {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: "What's the weather in San Francisco?"
        }
      };
    }
    
    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", "Perform calculations", { /* ... */ }, async (args) => { /* ... */ }),
        tool("translate", "Translate text", { /* ... */ }, async (args) => { /* ... */ }),
        tool("search_web", "Search the web", { /* ... */ }, async (args) => { /* ... */ })
      ]
    });
    
    // ストリーミング入力で特定のツールのみを許可
    async function* generateMessages() {
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: "Calculate 5 + 3 and translate 'hello' to Spanish"
        }
      };
    }
    
    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",
      "Process structured data with type safety",
      {
        // 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(`Processing ${args.data.name}'s data as ${args.format}`);
        
        // 処理ロジックをここに
        return {
          content: [{
            type: "text",
            text: `Processed data for ${args.data.name}`
          }]
        };
      }
    )

    エラーハンドリング

    意味のあるフィードバックを提供するために、エラーを適切に処理します:

    tool(
      "fetch_data",
      "Fetch data from an API",
      {
        endpoint: z.string().url().describe("API endpoint URL")
      },
      async (args) => {
        try {
          const response = await fetch(args.endpoint);
          
          if (!response.ok) {
            return {
              content: [{
                type: "text",
                text: `API error: ${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: `Failed to fetch data: ${error.message}`
            }]
          };
        }
      }
    )

    ツールの例

    データベースクエリツール

    const databaseServer = createSdkMcpServer({
      name: "database-tools",
      version: "1.0.0",
      tools: [
        tool(
          "query_database",
          "Execute a database query",
          {
            query: z.string().describe("SQL query to execute"),
            params: z.array(z.any()).optional().describe("Query parameters")
          },
          async (args) => {
            const results = await db.query(args.query, args.params || []);
            return {
              content: [{
                type: "text",
                text: `Found ${results.length} rows:\n${JSON.stringify(results, null, 2)}`
              }]
            };
          }
        )
      ]
    });

    APIゲートウェイツール

    const apiGatewayServer = createSdkMcpServer({
      name: "api-gateway",
      version: "1.0.0",
      tools: [
        tool(
          "api_request",
          "Make authenticated API requests to external services",
          {
            service: z.enum(["stripe", "github", "openai", "slack"]).describe("Service to call"),
            endpoint: z.string().describe("API endpoint path"),
            method: z.enum(["GET", "POST", "PUT", "DELETE"]).describe("HTTP method"),
            body: z.record(z.any()).optional().describe("Request body"),
            query: z.record(z.string()).optional().describe("Query parameters")
          },
          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",
          "Perform mathematical calculations",
          {
            expression: z.string().describe("Mathematical expression to evaluate"),
            precision: z.number().optional().default(2).describe("Decimal precision")
          },
          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: Invalid expression - ${error.message}`
                }]
              };
            }
          }
        ),
        tool(
          "compound_interest",
          "Calculate compound interest for an investment",
          {
            principal: z.number().positive().describe("Initial investment amount"),
            rate: z.number().describe("Annual interest rate (as decimal, e.g., 0.05 for 5%)"),
            time: z.number().positive().describe("Investment period in years"),
            n: z.number().positive().default(12).describe("Compounding frequency per year")
          },
          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: `Investment Analysis:\n` +
                      `Principal: $${args.principal.toFixed(2)}\n` +
                      `Rate: ${(args.rate * 100).toFixed(2)}%\n` +
                      `Time: ${args.time} years\n` +
                      `Compounding: ${args.n} times per year\n\n` +
                      `Final Amount: $${amount.toFixed(2)}\n` +
                      `Interest Earned: $${interest.toFixed(2)}\n` +
                      `Return: ${((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