# プロンプト

再利用可能なプロンプトテンプレートとワークフローを作成する

Promptsは、サーバーが再利用可能なプロンプトテンプレートとワークフローを定義することを可能にし、クライアントがユーザーやLLMに簡単に表示できるようにします。共通のLLMインタラクションを標準化し、共有する強力な方法を提供します。

Promptsは**ユーザー制御**を目的として設計されており、サーバーからクライアントに公開され、ユーザーがそれを明示的に選択して使用できるようにすることを意図しています。

## [概要](https://modelcontextprotocol.io/docs/concepts/prompts#overview)

MCPのPromptsは以下のことができます：

- 動的な引数を受け入れる
- リソースからコンテキストを含める
- 複数のインタラクションを連鎖させる
- 特定のワークフローをガイドする
- UI要素として表示される (スラッシュコマンドのように)

## [プロンプト構造](https://modelcontextprotocol.io/docs/concepts/prompts#prompt-structure)

各プロンプトは以下のように定義されます：

```typescript
{
  name: string;              // プロンプトのユニークな識別子
  description?: string;      // 人間が読める説明
  arguments?: [              // オプションの引数リスト
    {
      name: string;          // 引数の識別子
      description?: string;  // 引数の説明
      required?: boolean;    // 引数が必須かどうか
    }
  ]
}
```

## [プロンプトの発見](https://modelcontextprotocol.io/docs/concepts/prompts#discovering-prompts)

クライアントは`prompts/list`エンドポイントを通じて利用可能なプロンプトを発見できます：

```typescript
// Request
{
  method: "prompts/list"
}

// Response
{
  prompts: [
    {
      name: "analyze-code",
      description: "コードの改善点を分析する",
      arguments: [
        {
          name: "language",
          description: "プログラミング言語",
          required: true
        }
      ]
    }
  ]
}
```

## [プロンプトの使用](https://modelcontextprotocol.io/docs/concepts/prompts#using-prompts)

プロンプトを使用するために、クライアントは`prompts/get`リクエストを行います：

```typescript
// Request
{
  method: "prompts/get",
  params: {
    name: "analyze-code",
    arguments: {
      language: "python"
    }
  }
}

// Response
{
  description: "Pythonコードの改善点を分析する",
  messages: [
    {
      role: "user",
      content: {
        type: "text",
        text: "以下のPythonコードを潜在的な改善点について分析してください:\n\n```python\ndef calculate_sum(numbers):\n    total = 0\n    for num in numbers:\n        total = total + num\n    return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
      }
    }
  ]
}
```

## [動的プロンプト](https://modelcontextprotocol.io/docs/concepts/prompts#dynamic-prompts)

プロンプトは動的にし、以下を含むことができます：

### [埋め込みリソースコンテキスト](https://modelcontextprotocol.io/docs/concepts/prompts#embedded-resource-context)

```json
{
  "name": "analyze-project",
  "description": "プロジェクトのログとコードの分析",
  "arguments": [
    {
      "name": "timeframe",
      "description": "ログを分析する期間",
      "required": true
    },
    {
      "name": "fileUri",
      "description": "レビューするコードファイルのURI",
      "required": true
    }
  ]
}
```

`prompts/get`リクエストを処理する際：

```json
{
  "messages": [
    {
      "role": "user",
      "content": {
        "type": "text",
        "text": "これらのシステムログとコードファイルの問題を分析してください:"
      }
    },
    {
      "role": "user",
      "content": {
        "type": "resource",
        "resource": {
          "uri": "logs://recent?timeframe=1h",
          "text": "[2024-03-14 15:32:11] ERROR: 接続タイムアウト in network.py:127\n[2024-03-14 15:32:15] WARN: 再接続を試みています (試行 2/3)\n[2024-03-14 15:32:20] ERROR: 最大再試行回数を超えました",
          "mimeType": "text/plain"
        }
      }
    },
    {
      "role": "user",
      "content": {
        "type": "resource",
        "resource": {
          "uri": "file:///path/to/code.py",
          "text": "def connect_to_service(timeout=30):\n    retries = 3\n    for attempt in range(retries):\n        try:\n            return establish_connection(timeout)\n        except TimeoutError:\n            if attempt == retries - 1:\n                raise\n            time.sleep(5)\n\ndef establish_connection(timeout):\n    # サービスへの接続を確立する実装\n    pass",
          "mimeType": "text/x-python"
        }
      }
    }
  ]
}
```

### [マルチステップワークフロー](https://modelcontextprotocol.io/docs/concepts/prompts#multi-step-workflows)

```typescript
const debugWorkflow = {
  name: "debug-error",
  async getMessages(error: string) {
    return [
      {
        role: "user",
        content: {
          type: "text",
          text: `以下のエラーが発生しています: ${error}`
        }
      },
      {
        role: "assistant",
        content: {
          type: "text",
          text: "このエラーの分析を行います。これまでに試したことはありますか？"
        }
      },
      {
        role: "user",
        content: {
          type: "text",
          text: "サービスの再起動を試しましたが、エラーはまだ発生しています。"
        }
      }
    ];
  }
};
```

## [具体的な実装例](https://modelcontextprotocol.io/docs/concepts/prompts#example-implementation)

以下はMCPサーバーでプロンプトを実装する完全な例です：

- TypeScript

```typescript
import { Server } from "@modelcontextprotocol/sdk/server";
import {
  ListPromptsRequestSchema,
  GetPromptRequestSchema
} from "@modelcontextprotocol/sdk/types";

const PROMPTS = {
  "git-commit": {
    name: "git-commit",
    description: "Gitコミットメッセージを生成する",
    arguments: [
      {
        name: "changes",
        description: "Git diffまたは変更の説明",
        required: true
      }
    ]
  },
  "explain-code": {
    name: "explain-code",
    description: "コードの動作を説明する",
    arguments: [
      {
        name: "code",
        description: "説明対象のコード",
        required: true
      },
      {
        name: "language",
        description: "プログラミング言語",
        required: false
      }
    ]
  }
};

const server = new Server({
  name: "example-prompts-server",
  version: "1.0.0"
}, {
  capabilities: {
    prompts: {}
  }
});

// 利用可能なプロンプトのリスト
server.setRequestHandler(ListPromptsRequestSchema, async () => {
  return {
    prompts: Object.values(PROMPTS)
  };
});

// 特定のプロンプトを取得
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
  const prompt = PROMPTS[request.params.name];
  if (!prompt) {
    throw new Error(`プロンプトが見つかりません: ${request.params.name}`);
  }

  if (request.params.name === "git-commit") {
    return {
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `これらの変更に対して簡潔かつ説明的なコミットメッセージを生成してください:\n\n${request.params.arguments?.changes}`
          }
        }
      ]
    };
  }

  if (request.params.name === "explain-code") {
    const language = request.params.arguments?.language || "不明";
    return {
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `この${language}コードがどのように動作するかを説明してください:\n\n${request.params.arguments?.code}`
          }
        }
      ]
    };
  }

  throw new Error("プロンプトの実装が見つかりません");
});
```

## [ベストプラクティス](https://modelcontextprotocol.io/docs/concepts/prompts#best-practices)

プロンプトを実装する際には：

1. 明確で説明的なプロンプト名を使用する
2. プロンプトおよび引数の詳細な説明を提供する
3. すべての必須引数を検証する
4. 引数が見つからない場合は適切に処理する
5. プロンプトテンプレートのバージョニングを考慮する
6. 必要に応じて動的コンテンツをキャッシュする
7. エラーハンドリングを実装する
8. 想定される引数のフォーマットを文書化する
9. プロンプトの組み合わせ可能性を考慮する
10. さまざまな入力でプロンプトをテストする

## [UI統合](https://modelcontextprotocol.io/docs/concepts/prompts#ui-integration)

プロンプトはクライアントUIに以下の形で組み込むことができます：

- スラッシュコマンド
- クイックアクション
- コンテキストメニュー項目
- コマンドパレットエントリー
- ガイド付きワークフロー
- インタラクティブフォーム

## [更新と変更](https://modelcontextprotocol.io/docs/concepts/prompts#updates-and-changes)

サーバーはクライアントにプロンプトの変更を通知できます：

1. サーバー機能: `prompts.listChanged`
2. 通知: `notifications/prompts/list_changed`
3. クライアントはプロンプトリストを再取得

## [セキュリティ考慮事項](https://modelcontextprotocol.io/docs/concepts/prompts#security-considerations)

プロンプトを実装する際には：

- すべての引数を検証する
- ユーザー入力をサニタイズする
- レート制限を考慮する
- アクセス制御を実施する
- プロンプトの使用を監査する
- 機密データを適切に扱う
- 生成されたコンテンツを検証する
- タイムアウトを実装する
- プロンプトインジェクションのリスクを考慮する
- セキュリティ要件を文書化する
