エージェントを OpenAPI ツールに接続する

OpenAPI 3.0 および 3.1 仕様を使用して、Microsoft Foundry エージェントを外部 API に接続します。 エージェントを強化する Foundry モデルは、外部サービスの呼び出し、リアルタイム データの取得、組み込み関数以外の機能の拡張を行うことができます。

OpenAPI 仕様 では、既存のサービスをエージェントと統合できるように、HTTP API を記述する標準的な方法が定義されています。 Microsoft Foundry では、anonymousAPI key、および managed identity の 3 つの認証方法がサポートされています。 認証方法の選択については、「認証方法 の選択」を参照してください。

ヒント

ツールボックスを使用してこのツールを追加することを検討 してください。 ツールボックスを使用すると、エージェントとランタイム間でツールを再利用できるほか、マネージド MCP エンドポイントを介して資格情報の管理、バージョン管理、ポリシーの適用を一元化できます。 ツールボックスの クイック スタートを参照してください。

前提 条件

開始する前に、次の内容を確認してください。

  • 適切なアクセス許可を持つAzure サブスクリプション。

  • エージェントを作成して実行するための Foundry プロジェクトの Foundry ユーザー ロール。

    重要

    Foundry RBAC ロールの名前が最近変更されました。 Foundry User, Foundry Owner, Foundry Account Owner、および Foundry Project Manager は、以前は、AZURE AI ユーザー、Azure AI 所有者、Azure AI アカウント所有者、および AZURE AI Project Manager という名前でした。 名前の変更がロールアウトされている間、以前の名前が表示される場合があります。ロール ID とコア アクセス許可は、名前の変更によって変更されません。

  • API キーまたはトークン認証用のプロジェクト接続を作成する場合は、Foundry プロジェクトで Foundry Project Manager ロールが必要です。

  • エンドポイントが構成された Foundry プロジェクト。

  • プロジェクトにデプロイされた AI モデル。 モデルとプロジェクトリージョンの両方が、 リージョンとモデル別のツールで OpenAPI ツールをサポートしていることを確認します。

  • 基本または標準のエージェント環境

  • お好みの言語用にインストールされた SDK:

    • パイソン: pip install azure-ai-projects jsonref
    • C#: Azure.AI.Extensions.OpenAI
    • TypeScript/JavaScript: @azure/ai-projects
    • ジャワ: com.azure:azure-ai-agents

環境変数

変数 説明
FOUNDRY_PROJECT_ENDPOINT Foundry プロジェクト エンドポイントの URL (外部の OpenAPI サービス エンドポイントではありません)。
FOUNDRY_MODEL_DEPLOYMENT_NAME デプロイされたモデル名。
OPENAPI_PROJECT_CONNECTION_NAME (API キー認証の場合)OpenAPI サービスのプロジェクト接続名。
  • 次の要件を満たす OpenAPI 3.0 または 3.1 仕様ファイル:
    • 各関数には、(OpenAPI ツールに必要な) operationId が必要です。
    • operationId には、文字、 -、および _のみを含める必要があります。
    • モデルが使用する関数を効率的に決定するのに役立つわかりやすい名前を使用します。
    • サポートされている要求本文のコンテンツ タイプ: application/jsonapplication/json-patch+json
  • マネージド ID 認証の場合: 必要な API 操作を許可する最小特権のターゲット サービス ロール。ターゲット リソース スコープで Foundry プロジェクトのマネージド ID に割り当てられます。
  • API キー/トークン認証の場合: API キーまたはトークンで構成されたプロジェクト接続。 プロジェクトへの新しい接続の追加を参照してください

メモ

FOUNDRY_PROJECT_ENDPOINT 値は、外部の OpenAPI サービス エンドポイントではなく、Microsoft Foundry プロジェクト エンドポイントを参照します。 このエンドポイントは、Microsoft Foundry ポータルのプロジェクトの [概要] ページにあります。 このエンドポイントは、エージェント サービスを認証するために必要であり、仕様ファイルで定義されている OpenAPI エンドポイントとは別です。

使用サポート

次の表に、SDK とセットアップのサポートを示します。

Microsoft Foundry のサポート Python SDK C# SDK JavaScript SDK Java SDK REST API 基本的なエージェントのセットアップ 標準エージェントのセットアップ
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

メモ

Javaの場合は、OpenAPI エージェント ツールの com.azure:azure-ai-agents パッケージを使用します。 com.azure:azure-ai-projects パッケージは現在、OpenAPI エージェント ツールの種類を公開していません。

匿名の最初の成功フローを実行する

匿名天気 API から始めて、エージェントが OpenAPI 仕様を読み込んで操作を呼び出すことができることを確認します。 このパスには、外部 API 資格情報または Foundry プロジェクト接続は必要ありません。

  1. [前提条件] から選択した言語の SDK パッケージをインストールします。
  2. weather_openapi.jsonをダウンロードし、サンプルで使用されているassets パスに保存します。
  3. Foundry プロジェクトのエンドポイントとモデルのデプロイ値を設定します。
  4. 選択した言語セクションで匿名サンプルを実行します。
  5. 応答にシアトルの現在の天気が含まれていることを確認し、サンプルによって作成されたエージェントのバージョンを削除します。

匿名呼び出しが成功したら、ターゲット API に必要な認証を構成します。 API キー認証ベアラー トークン認証マネージド ID 認証は個別のバリアントとして保持します。

制限事項を理解する

  • OpenAPI 仕様には各操作の operationId を含める必要があり、 operationId には文字、 -、および _のみを含めることができます。
  • サポートされている要求本文のコンテンツ タイプ: application/jsonapplication/json-patch+json
  • API キー認証の場合は、OpenAPI ツールごとに 1 つの API キー セキュリティ スキームを使用します。 複数のセキュリティ スキームが必要な場合は、複数の OpenAPI ツールを作成します。
  • API キーとベアラー トークンを、公開の疑いがある直後に定期的にローテーションします。 資格情報が変更されたときにプロジェクト接続を更新します。OpenAPI 仕様またはソース コードに資格情報を配置しないでください。

ツールボックスに OpenAPI ツールを追加する

OpenAPI 仕様で記述されている REST API を公開するには、このパターンを使用します。API のセキュリティ モデルに一致する auth.type を選択します。

重要

マネージド ID 認証を使用する場合は、必要な API 操作を許可する最小特権 RBAC ロールのみを、ターゲット サービス上 の Foundry プロジェクトの マネージド ID に割り当てます。 たとえば、API に読み取り専用のAzure Resource Manager アクセスが必要な場合にのみ、ターゲット Azure リソースに Reader を割り当てます。 必要な割り当てがない場合、エージェントは API の呼び出し時に 401 Unauthorized 応答を受け取ります。 完全なセットアップ手順については、「 マネージド ID を使用した認証」を参照してください。

匿名認証:

{
  "description": "REST API via OpenAPI spec",
  "tools": [
    {
      "type": "openapi",
      "openapi": {
        "name": "my-api",
        "spec": { "<paste OpenAPI spec object here>" },
        "auth": {
          "type": "anonymous"
        }
      }
    }
  ]
}

プロジェクト接続認証:

このパターンは、API で Foundry プロジェクト接続に格納されているキーまたはトークンが必要な場合に使用します。

{
  "description": "REST API with connection-based auth",
  "tools": [
    {
      "type": "openapi",
      "openapi": {
        "name": "my-api",
        "spec": { "<paste OpenAPI spec object here>" },
        "auth": {
          "type": "connection",
          "security_scheme": {
            "project_connection_id": "<CONNECTION_NAME>"
          }
        }
      }
    }
  ]
}

マネージド ID 認証:

ターゲット API が Microsoft Entra ID を使用して認証する場合は、このパターンを使用します。 Foundry プロジェクトのマネージド ID は、エージェントの代わりに API を呼び出します。 このパターンを使用する前に、マネージド ID にターゲット サービスに必要な RBAC ロールがあることを確認します。

{
  "description": "REST API with managed identity auth",
  "tools": [
    {
      "type": "openapi",
      "openapi": {
        "name": "my-api",
        "spec": { "<paste OpenAPI spec object here>" },
        "auth": {
          "type": "managed_identity",
          "security_scheme": {
            "audience": "<TARGET_SERVICE_AUDIENCE>"
          }
        }
      }
    }
  ]
}
from azure.ai.projects.models import OpenAPITool

tools = [
    OpenAPITool(
        name="my-api",
        spec={"<paste OpenAPI spec object here>"},
        auth={"type": "anonymous"},
    )
]
BinaryData specBytes = BinaryData.FromString("<OpenAPI spec JSON>");
ProjectsAgentTool tool = new OpenAPITool(
    new OpenApiFunctionDefinition(
        name: "my-api",
        spec: specBytes,
        openApiAuthentication: new OpenApiAnonymousAuthDetails()
    )
);

ToolboxVersion toolboxVersion = await toolboxClient.CreateToolboxVersionAsync(
    toolboxName: "my-toolbox",
    tools: [tool],
    description: "REST API via OpenAPI spec"
);
const tools = [
  {
    type: "openapi",
    openapi: {
      name: "my-api",
      spec: { /* paste OpenAPI spec object here */ },
      auth: {
        type: "anonymous",
      },
    },
  },
];

Azure Developer CLI を使用して OpenAPI ツールボックスを作成する

OpenAPI ツールは、 tools:のすぐ下にスペックを埋め込みます。 接続ベースの認証 (connection_auth) はプロジェクト接続を参照します。匿名の OpenAPI ツールには接続は必要ありません。

ステップ 1. (省略可能)認証接続を作成する

匿名の OpenAPI ツールの場合は、この手順をスキップします。

# API-key auth (passed by the platform on every call)
# Set OPENAPI_AUTHORIZATION_HEADER in your shell without committing its value.
azd ai connection create my-api-conn \
  --kind remote-tool \
  --target https://api.example.com \
  --auth-type custom-keys \
  --custom-key "Authorization=$OPENAPI_AUTHORIZATION_HEADER"

OpenAPI ツールは、 --auth-type oauth2 接続も受け入れます。 azd ai connection create フラグの完全なセットについては、「ツールボックス MCP 認証と構成」を参照してください。

ステップ 2. ツールボックスを定義する

OpenAPI 仕様は、 tools[].openapi.specの下にインラインで表示されます。

# my-toolbox.yaml
description: OpenAPI toolbox
tools:
  - type: openapi
    name: my-api
    openapi:
      name: my-api
      spec:
        openapi: "3.0.1"
        info:
          title: "My API"
          version: "1.0"
        servers:
          - url: https://api.example.com/v1
        paths:
          /search:
            get:
              operationId: search
              parameters:
                - name: query
                  in: query
                  required: true
                  schema:
                    type: string
              responses:
                "200":
                  description: OK
      auth:
        type: connection_auth
        connection_id: my-api-conn

匿名 API の場合は、 auth: ブロックを次のように置き換えます。

      auth:
        type: anonymous
        security_scheme:
          type: anonymous

ステップ 3. ツールボックスを作成する

azd ai toolbox create my-toolbox --from-file my-toolbox.yaml

コード サンプルを実行する前に

  • 管理されている tripadvisor_openapi.json 仕様をダウンロードし、言語サンプルで使用されている assets パスに保存します。

メモ

  • 最新の SDK パッケージが必要です。 .NET SDK は現在プレビュー段階です。 詳細については、 クイック スタート を参照してください。
  • 認証に API キーを使用する場合、接続 ID は /subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}} の形式にする必要があります。

重要

API キー認証を機能させるには、OpenAPI 仕様ファイルに次のものが含まれている必要があります。

  1. ヘッダー名やパラメーター名など、API キー構成を含む securitySchemes セクション。
  2. セキュリティ スキームを参照する security セクション。
  3. 一致するキーの名前と値で構成されたプロジェクト接続。

これらの構成がないと、API キーは要求に含まれません。 詳細なセットアップ手順については、「 API キーを使用した認証」 セクションを参照してください。

トークンをプロジェクト接続に格納することで、トークン ベースの認証 (ベアラー トークンなど) を使用することもできます。 ベアラー トークン認証の場合は、キーが に設定され、値が Authorization に設定されたBearer <token>接続を作成します (<token>を実際のトークンに置き換えます)。 Bearer後にスペースが続く単語は、値に含まれている必要があります。 詳細については、「 ベアラー トークン接続の設定」を参照してください。

OpenAPI ツールでのエージェントの使用のサンプル

この例では、エージェントを使用して OpenAPI 仕様 で説明されているサービスを使用する方法を示します。 wttr.in サービスを使用して、天気とその仕様ファイル weather_openapi.jsonを取得します。 Prompt Agents を選択して、Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成するか、Hosted Agents を使用して、Microsoft Agent Framework を使用してエフェメラルなインプロセス エージェントを構築します。

エージェントに指示を促す

import os
import jsonref
from typing import Any, cast
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    PromptAgentDefinition,
    OpenApiTool,
    OpenApiFunctionDefinition,
    OpenApiAnonymousAuthDetails,
)

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(
    endpoint=PROJECT_ENDPOINT,
    credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()

weather_asset_file_path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../assets/weather_openapi.json")
)

with open(weather_asset_file_path, "r") as f:
    openapi_weather = cast(dict[str, Any], jsonref.loads(f.read()))

# Initialize agent OpenAPI tool using the read in OpenAPI spec
weather_tool = OpenApiTool(
    openapi=OpenApiFunctionDefinition(
        name="get_weather",
        spec=openapi_weather,
        description="Retrieve weather information for a location.",
        auth=OpenApiAnonymousAuthDetails(),
    )
)

agent = project.agents.create_version(
    agent_name="MyAgent",
    definition=PromptAgentDefinition(
        model="gpt-4.1-mini",
        instructions="You are a helpful assistant.",
        tools=[weather_tool],
    ),
)
response = openai.responses.create(
    input="What's the weather in Seattle?",
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(response.output_text)

# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)

この例では、匿名認証を使用して wttr.in weather API を呼び出す OpenAPI ツールを使用してプロンプト エージェントを作成します。 ツールはエージェント定義に直接アタッチされます。 コードを実行する場合:

  1. ローカル JSON ファイルから天気 OpenAPI 仕様が読み込まれます。
  2. 匿名アクセス用に構成された天気ツールを使用して、プロンプト エージェントを作成します。
  3. シアトルの天気について質問するクエリを送信します。
  4. エージェントは OpenAPI ツールを使用して Weather API を呼び出し、書式設定された結果を返します。
  5. エージェントのバージョンを削除してクリーンアップします。

ホスト型エージェント

このサンプルでは、Microsoft Agent Framework からのFoundryChatClientを使用し、FoundryToolboxを使用してツールボックス MCP エンドポイントに接続します。 pip install "agent-framework-foundry==1.10.4" "azure-ai-projects>=2.3.0,<2.4.0" azure-identity jsonrefと互換性のあるパッケージ バージョンをインストールし、FOUNDRY_PROJECT_ENDPOINT環境変数を設定して、az loginでサインインします。 OpenApiToolboxTool はツールボックス固有のモデルです。 OpenApiTool は、ツールをプロンプト エージェントに直接アタッチする場合にのみ使用します。

import asyncio
import os
import jsonref
from typing import Any, cast

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    OpenApiToolboxTool,
    OpenApiFunctionDefinition,
    OpenApiAnonymousAuthDetails,
)

PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"


async def main() -> None:
    credential = AzureCliCredential()

    # 1. Create the OpenAPI tool and add it to a toolbox. Using a toolbox is the
    #    recommended way to give agents tools: curate tools once and reuse the
    #    toolbox across agents. See /azure/foundry/agents/concepts/toolbox-overview
    project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)

    weather_asset_file_path = os.path.abspath(
        os.path.join(os.path.dirname(__file__), "../assets/weather_openapi.json")
    )
    with open(weather_asset_file_path, "r") as f:
        openapi_weather = cast(dict[str, Any], jsonref.loads(f.read()))

    weather_tool = OpenApiToolboxTool(
        openapi=OpenApiFunctionDefinition(
            name="get_weather",
            spec=openapi_weather,
            description="Retrieve weather information for a location.",
            auth=OpenApiAnonymousAuthDetails(),
        )
    )

    toolbox = project.toolboxes.create_version(
        name="openapi-toolbox",
        description="Toolbox with the OpenAPI weather tool",
        tools=[weather_tool],
    )

    # 2. The toolbox exposes an MCP-compatible endpoint.
    TOOLBOX_MCP_URL = (
        f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
        f"/versions/{toolbox.version}/mcp?api-version=v1"
    )

    # 3. Attach the toolbox to the hosted agent as an MCP tool.
, timeout=120.0)
    toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)

agent = Agent(
        client=FoundryChatClient(credential=credential),
        instructions="You are a helpful assistant. Use the OpenAPI weather tool to answer questions.",
        tools=[toolbox_tool],
    )

    result = await agent.run("What's the weather in Seattle?")
    print(f"Agent: {result.text}")


if __name__ == "__main__":
    asyncio.run(main())

予期される出力

Agent: The weather in Seattle is currently cloudy with a temperature of 52°F (11°C)...

OpenAPI ツールでのエージェントの使用のサンプル

この例では、エージェントを使用して OpenAPI 仕様 で説明されているサービスを使用する方法を示します。 wttr.in サービスを使用して、天気とその仕様ファイル weather_openapi.jsonを取得します。 Prompt Agents を選択して、Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成するか、Hosted Agents を使用して、Microsoft Agent Framework を使用してエフェメラルなインプロセス エージェントを構築します。

エージェントに指示を促す

この例では、Azure AI Projects クライアント ライブラリの同期メソッドを使用します。 非同期メソッドを使用する例については、GitHubの.NETリポジトリのAzure SDKのsampleを参照してください。

using System;
using System.IO;
using System.Runtime.CompilerServices;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;

class OpenAPIDemo
{
    // Utility method to get the OpenAPI specification file from the Assets folder.
    private static string GetFile([CallerFilePath] string pth = "")
    {
        var dirName = Path.GetDirectoryName(pth) ?? "";
        return Path.Combine(dirName, "Assets", "weather_openapi.json");
    }

    public static void Main()
    {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        var projectEndpoint = "your_project_endpoint";

        // Create project client to call Foundry API
        AIProjectClient projectClient = new(
            endpoint: new Uri(projectEndpoint),
            tokenProvider: new DefaultAzureCredential());

        // Create an Agent with `OpenAPIAgentTool` and anonymous authentication.
        string filePath = GetFile();
        OpenAPIFunctionDefinition toolDefinition = new(
            name: "get_weather",
            spec: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
            auth: new OpenAPIAnonymousAuthenticationDetails()
        );
        toolDefinition.Description = "Retrieve weather information for a location.";
        OpenAPITool openapiTool = new(toolDefinition);

        // Create the agent definition and the agent version.
        DeclarativeAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
        {
            Instructions = "You are a helpful assistant.",
            Tools = { openapiTool }
        };
        AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
            agentName: "myAgent",
            options: new(agentDefinition));

        // Create a response object and ask the question about the weather in Seattle, WA.
        ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
        ResponseResult response = responseClient.CreateResponse(
                userInputText: "Use the OpenAPI tool to print out, what is the weather in Seattle, WA today."
            );
        Console.WriteLine(response.GetOutputText());

        // Finally, delete all the resources created in this sample.
        projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
    }
}

このコードの動作

この C# の例では、匿名認証を使用して wttr.in から気象情報を取得する OpenAPI ツールを使用してエージェントを作成します。 コードを実行する場合:

  1. ローカル JSON ファイルから天気 OpenAPI 仕様を読み取ります。
  2. 気象ツールが構成されたエージェントを作成します。
  3. OpenAPI ツールを使用して、シアトルの天気に関する要求を送信します。
  4. エージェントは weather API を呼び出し、結果を返します。
  5. エージェントを削除してクリーンアップします。

必要な入力

  • インライン文字列値: projectEndpoint(あなたのFoundryプロジェクトエンドポイント)
  • ローカル ファイル: Assets/weather_openapi.json (OpenAPI 仕様)

予期される出力

The weather in Seattle, WA today is cloudy with temperatures around 52°F...

一般的なエラー

  • FileNotFoundException: Assets フォルダーに OpenAPI 仕様ファイルが見つかりません
  • UnauthorizedAccessException: 無効な資格情報または RBAC アクセス許可が不十分です
  • API キーが挿入されない: OpenAPI 仕様に、スキーム名が一致する securitySchemes ( components) セクションと security セクションの両方が含まれていることを確認します

ホスト型エージェント

このサンプルでは、Azure AI Projects SDK を使用して OpenAPI ツールボックスを作成し、Microsoft Agent Framework AddFoundryToolboxes統合を使用して、ツールをホストされたエージェントで使用できるようにします。 Agent Framework パッケージをインストールし、 AZURE_AI_PROJECT_ENDPOINT プロジェクト エンドポイントと AZURE_AI_MODEL_DEPLOYMENT_NAME 環境変数を設定し、 az loginでサインインします。

using System.IO;
using System.Runtime.CompilerServices;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;

string GetFile([CallerFilePath] string pth = "")
{
    var dirName = Path.GetDirectoryName(pth) ?? "";
    return Path.Combine(dirName, "Assets", "weather_openapi.json");
}

string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
    ?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";

var openAiEndpoint = new Uri(projectEndpoint).GetLeftPart(UriPartial.Authority);
DefaultAzureCredential credential = new();

// 1. Create the OpenAPI tool and add it to a toolbox. Using a toolbox is the
//    recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: credential);
string filePath = GetFile();
OpenAPIFunctionDefinition toolDefinition = new(
    name: "get_weather",
    spec: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
    auth: new OpenAPIAnonymousAuthenticationDetails()
);
toolDefinition.Description = "Retrieve weather information for a location.";
ProjectsAgentTool openapiTool = new OpenAPITool(toolDefinition);
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
    .GetAgentToolboxes().CreateToolboxVersion(
        toolboxName: "openapi-toolbox",
        tools: [openapiTool],
        description: "Toolbox with the OpenAPI weather tool");

// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
    model: deploymentName,
    instructions: "You are a helpful assistant with access to the toolbox tools.",
    name: "hosted-toolbox-agent");

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);

var app = builder.Build();
app.MapFoundryResponses();
app.Run();

予期される出力

エージェントは OpenAPI ツールを使用して weather API を呼び出し、要求された場所の現在の条件を返します。

The current weather in Seattle is <temperature> with <conditions>.

認証された API パターンを含む完全なサンプルについては、 Agent_Step17_OpenAPIToolsを参照してください。


認証が必要な Web サービス上の OpenAPI ツールでエージェントを使用するサンプル

この例では、認証された OpenAPI ツールをツールボックスに追加し、ツールボックスを MCP ツールとしてアタッチし、認証が必要なシナリオでエージェントを使用します。 TripAdvisor 仕様を使用します。

TripAdvisor サービスには、キーベースの認証が必要です。 接続を作成するには、Foundry Microsoft開き、右上のナビゲーションで [管理] を選択し、Project詳細を選択して、[接続済みリソース] タブを選択します。最後に、カスタム キーの種類の新しい接続を作成します。 tripadvisor名前を付け、キーと値のペアを追加します。 keyという名前のキーを追加し、TripAdvisor キーを使用して値を入力します。

class OpenAPIConnectedDemo
{
    // Utility method to get the OpenAPI specification file from the Assets folder.
    private static string GetFile([CallerFilePath] string pth = "")
    {
        var dirName = Path.GetDirectoryName(pth) ?? "";
        return Path.Combine(dirName, "Assets", "tripadvisor_openapi.json");
    }

    public static void Main()
    {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        var projectEndpoint = "your_project_endpoint";

        // Create project client to call Foundry API
        AIProjectClient projectClient = new(
            endpoint: new Uri(projectEndpoint),
            tokenProvider: new DefaultAzureCredential());

        // Create an OpenAPI tool with authentication by project connection security scheme.
        string filePath = GetFile();
        AIProjectConnection tripadvisorConnection = projectClient.Connections.GetConnection("tripadvisor");
        OpenAPIFunctionDefinition toolDefinition = new(
            name: "tripadvisor",
            spec: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
            auth: new OpenAPIProjectConnectionAuthenticationDetails(new OpenAPIProjectConnectionSecurityScheme(
                projectConnectionId: tripadvisorConnection.Id
            ))
        );
        toolDefinition.Description = "Trip Advisor API to get travel information.";
        ProjectsAgentTool openapiTool = new OpenAPITool(toolDefinition);

        // 1. Add the authenticated OpenAPI tool to a toolbox. Using a toolbox is the
        //    recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
        AgentToolboxes toolboxClient = projectClient.AgentAdministrationClient.GetAgentToolboxes();

        ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
            .GetAgentToolboxes().CreateToolboxVersion(
                toolboxName: "openapi-toolbox",
                tools: [openapiTool],
                description: "Toolbox with the authenticated TripAdvisor OpenAPI tool");

        // 2. The toolbox exposes an MCP-compatible endpoint.
        var toolboxMcpUrl = new Uri(
            $"{projectEndpoint}/toolboxes/{toolboxVersion.Name}" +
            $"/versions/{toolboxVersion.Version}/mcp?api-version=v1");

        // 3. Create a remote-tool project connection that points at the toolbox endpoint.
        //    Use a user Entra token so the caller's identity is passed through
        //    (audience https://ai.azure.com). Create the connection once, for example
        //    with the Azure Developer CLI:
        //
        //    azd ai connection create openapi-toolbox-conn \
        //      --kind remote-tool \
        //      --target "<toolboxMcpUrl>" \
        //      --auth-type user-entra-token \
        //      --audience https://ai.azure.com
        var toolboxConnectionName = "openapi-toolbox-conn";

        // 4. Attach the toolbox to a prompt agent as an MCP tool.
        McpTool toolboxTool = ResponseTool.CreateMcpTool(
            serverLabel: "toolbox",
            serverUri: toolboxMcpUrl,
            toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
                GlobalMcpToolCallApprovalPolicy.NeverRequireApproval));
        toolboxTool.ProjectConnectionId = toolboxConnectionName;

        // Create the agent definition and the agent version.
        DeclarativeAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
        {
            Instructions = "You are a helpful assistant.",
            Tools = { toolboxTool }
        };
        AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
            agentName: "myAgent",
            options: new(agentDefinition));

        // Create a response object and ask the question about the hotels in France.
        // Test the Web service access before you run production scenarios.
        // It can be done by setting:
        // ToolChoice = ResponseToolChoice.CreateRequiredChoice()`
        // in the ResponseCreationOptions. This setting will
        // force Agent to use tool and will trigger the error if it is not accessible.
        ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
        CreateResponseOptions responseOptions = new()
        {
            ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
            InputItems =
            {
                ResponseItem.CreateUserMessageItem("Recommend me 5 top hotels in paris, France."),
            }
        };
        ResponseResult response = responseClient.CreateResponse(
            options: responseOptions
        );
        Console.WriteLine(response.GetOutputText());

        // Finally, delete all the resources we have created in this sample.
        projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
    }
}

このコードの動作

この C# の例では、ツールボックスとプロジェクト接続を介した API キー認証で OpenAPI ツールを使用する方法を示します。 コードを実行する場合:

  1. ローカル ファイルから TripAdvisor OpenAPI 仕様を読み込みます。
  2. API キーを含む tripadvisor プロジェクト接続を取得します。
  3. 接続を認証に使用するように構成された TripAdvisor ツールを含むツールボックス バージョンを作成します。
  4. ツールボックスを MCP ツールとしてエージェントにアタッチします。
  5. パリのホテルおすすめリクエストを送信します。
  6. エージェントは、格納されている API キーを使用して TripAdvisor API を呼び出し、結果を返します。
  7. エージェントを削除してクリーンアップします。

必要な入力

  • インライン文字列値: projectEndpoint(あなたのFoundryプロジェクトエンドポイント)
  • ローカル ファイル: Assets/tripadvisor_openapi.json
  • 有効なAPIキーが構成されたプロジェクト接続: tripadvisor

予期される出力

Here are 5 top hotels in Paris, France:
1. Hotel Name - Rating: 4.5/5, Location: ...
2. Hotel Name - Rating: 4.4/5, Location: ...
...

一般的なエラー

  • ConnectionNotFoundException: tripadvisor という名前のプロジェクト接続が見つかりません。
  • AuthenticationException: プロジェクト接続の API キーが無効であるか、OpenAPI 仕様の securitySchemes 構成が見つからない、または正しくない。
  • ツールが使用されていないことを確認してください: ToolChoice = ResponseToolChoice.CreateRequiredChoice() がツールの使用を強制しているかを検証します。
  • API キーが API に渡されない: OpenAPI 仕様に適切な securitySchemessecurity セクションが構成されていることを確認します。

OpenAPI ツール機能を使用してJava エージェントを作成する

このJavaセットアップでは MCP ツールを参照できますが、Java SDK はまだツールボックス作成 API を公開していません。

ヒント

推奨: ほとんどのエージェントでは、 ツールボックス から OpenAPI ツールを追加し、MCP ツールとしてツールボックスをエージェントにアタッチします。 PythonREST APIC#TypeScript の例、または Foundry ポータルを使用してツールボックスを作成し、Java エージェントから MCP エンドポイントをMcpToolとして参照します。

次の例は、REST API を使用して OpenAPI ツールを呼び出す方法を示しています。

アクセス トークンを取得します。

AGENT_TOKEN=$(az account get-access-token --scope https://ai.azure.com/.default --query accessToken -o tsv)

匿名認証

ツールボックスを使用して OpenAPI ツールを追加し、MCP ツールとしてツールボックスをエージェントにアタッチします。 詳細については、「ツールボックスとは」を参照してください。

  1. OpenAPI 天気ツールを含むツールボックスを作成します。
curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions?api-version=v1" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "description": "Toolbox with the OpenAPI weather tool",
    "tools": [
      {
        "type": "openapi",
        "openapi": {
          "name": "weather",
          "description": "Tool to get weather data",
          "auth": { "type": "anonymous" },
          "spec": {
            "openapi": "3.1.0",
            "info": {
              "title": "get weather data",
              "description": "Retrieves current weather data for a location.",
              "version": "v1.0.0"
            },
            "servers": [{ "url": "https://wttr.in" }],
            "paths": {
              "/{location}": {
                "get": {
                  "description": "Get weather information for a specific location",
                  "operationId": "GetCurrentWeather",
                  "parameters": [
                    {
                      "name": "location",
                      "in": "path",
                      "description": "City or location to retrieve the weather for",
                      "required": true,
                      "schema": { "type": "string" }
                    },
                    {
                      "name": "format",
                      "in": "query",
                      "description": "Format in which to return data. Always use 3.",
                      "required": true,
                      "schema": { "type": "integer", "default": 3 }
                    }
                  ],
                  "responses": {
                    "200": {
                      "description": "Successful response",
                      "content": {
                        "text/plain": {
                          "schema": { "type": "string" }
                        }
                      }
                    },
                    "404": { "description": "Location not found" }
                  }
                }
              }
            }
          }
        }
      }
    ]
  }'

ツールボックスは、 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1で MCP 互換エンドポイントを公開します。ここで、 <version> は前の呼び出しによって返されたバージョンです。

  1. 呼び出し元の ID が渡されるようにユーザー Entra トークンを使用して、ツールボックス エンドポイントを指すリモート ツール プロジェクト接続を作成します (対象ユーザー https://ai.azure.com)。
azd ai connection create openapi-toolbox-conn \
  --kind remote-tool \
  --target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1" \
  --auth-type user-entra-token \
  --audience https://ai.azure.com
  1. ツールボックスを MCP ツールとしてアタッチして、ツールボックスを使用する応答を作成します。
curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  --header "Authorization: Bearer $AGENT_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
    "input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
    "tool_choice": "required",
    "tools": [
      {
        "type": "mcp",
        "server_label": "toolbox",
        "server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1",
        "require_approval": "never",
        "project_connection_id": "openapi-toolbox-conn"
      }
    ]
  }'

API キー認証 (プロジェクト接続)

匿名フローが成功した後にのみ、このバリアントを使用します。 API キーで認証で説明されているように、プロジェクト接続と OpenAPI securitySchemes エントリを構成します。

curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  --header "Authorization: Bearer $AGENT_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
    "input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
    "tools": [
      {
        "type": "openapi",
        "openapi": {
          "name": "weather",
          "description": "Tool to get weather data",
          "auth": {
            "type": "project_connection",
            "security_scheme": {
              "project_connection_id": "'$WEATHER_APP_PROJECT_CONNECTION_ID'"
            }
          },
          "spec": {
            "openapi": "3.1.0",
            "info": {
              "title": "get weather data",
              "description": "Retrieves current weather data for a location.",
              "version": "v1.0.0"
            },
            "servers": [{ "url": "https://wttr.in" }],
            "paths": {
              "/{location}": {
                "get": {
                  "description": "Get weather information for a specific location",
                  "operationId": "GetCurrentWeather",
                  "parameters": [
                    {
                      "name": "location",
                      "in": "path",
                      "description": "City or location to retrieve the weather for",
                      "required": true,
                      "schema": { "type": "string" }
                    },
                    {
                      "name": "format",
                      "in": "query",
                      "description": "Format in which to return data. Always use 3.",
                      "required": true,
                      "schema": { "type": "integer", "default": 3 }
                    }
                  ],
                  "responses": {
                    "200": {
                      "description": "Successful response",
                      "content": {
                        "text/plain": {
                          "schema": { "type": "string" }
                        }
                      }
                    },
                    "404": { "description": "Location not found" }
                  }
                }
              }
            },
            "components": {
              "securitySchemes": {
                "apiKeyHeader": {
                  "type": "apiKey",
                  "name": "x-api-key",
                  "in": "header"
                }
              }
            },
            "security": [
              { "apiKeyHeader": [] }
            ]
          }
        }
      }
    ]
  }'

ベアラー トークン API の場合は、同じ project_connection 要求の形状を維持しますが、「 ベアラー トークン接続の設定」の説明に従って構成された接続を使用します。 接続値は、 Bearer で始まり、その後にスペースが続く必要があります。

マネージド ID 認証

curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  --header "Authorization: Bearer $AGENT_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
    "input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
    "tools": [
      {
        "type": "openapi",
        "openapi": {
          "name": "weather",
          "description": "Tool to get weather data",
          "auth": {
            "type": "managed_identity",
            "security_scheme": {
              "audience": "'$MANAGED_IDENTITY_AUDIENCE'"
            }
          },
          "spec": {
            "openapi": "3.1.0",
            "info": {
              "title": "get weather data",
              "description": "Retrieves current weather data for a location.",
              "version": "v1.0.0"
            },
            "servers": [{ "url": "https://wttr.in" }],
            "paths": {
              "/{location}": {
                "get": {
                  "description": "Get weather information for a specific location",
                  "operationId": "GetCurrentWeather",
                  "parameters": [
                    {
                      "name": "location",
                      "in": "path",
                      "description": "City or location to retrieve the weather for",
                      "required": true,
                      "schema": { "type": "string" }
                    },
                    {
                      "name": "format",
                      "in": "query",
                      "description": "Format in which to return data. Always use 3.",
                      "required": true,
                      "schema": { "type": "integer", "default": 3 }
                    }
                  ],
                  "responses": {
                    "200": {
                      "description": "Successful response",
                      "content": {
                        "text/plain": {
                          "schema": { "type": "string" }
                        }
                      }
                    },
                    "404": { "description": "Location not found" }
                  }
                }
              }
            }
          }
        }
      }
    ]
  }'

このコードの動作

この REST API の例では、さまざまな認証方法で OpenAPI ツールを呼び出す方法を示します。 要求:

  1. 匿名認証の場合は、OpenAPI ツール定義と天気 API 仕様を含むツールボックスを作成します。
  2. ツールボックスを MCP ツールとして添付し、シアトルの天気について尋ねる応答を作成します。
  3. プロジェクト接続とマネージド ID 認証を使用した API キーの追加の直接 REST ツール定義を示します。
  4. エージェントはツールを使用して weather API を呼び出し、書式設定された結果を返します。

必要な入力

  • 環境変数: FOUNDRY_PROJECT_ENDPOINTAGENT_TOKENFOUNDRY_MODEL_DEPLOYMENT_NAME
  • API キー認証の場合: WEATHER_APP_PROJECT_CONNECTION_ID
  • マネージド ID 認証の場合: MANAGED_IDENTITY_AUDIENCE
  • 要求本文でのインライン OpenAPI 仕様。

予期される出力

{
  "id": "resp_abc123",
  "object": "response",
  "output": [
    {
      "type": "message",
      "content": [
        {
          "type": "text",
          "text": "The weather in Seattle, WA today is cloudy with a temperature of 52°F (11°C)..."
        }
      ]
    }
  ]
}

一般的なエラー

  • 401 Unauthorized: OpenAPI 仕様にAGENT_TOKENsecuritySchemesがないため、無効または不足しているsecurity、または API キーが挿入されていません
  • 404 Not Found: エンドポイントまたはモデルのデプロイ名が正しくありません
  • 400 Bad Request: OpenAPI 仕様の形式が正しくないか、認証構成が無効です
  • 要求と共に送信されない API キー: OpenAPI 仕様の components.securitySchemes セクションが正しく構成されており (空ではない)、プロジェクト接続キー名と一致するかどうかを確認します

OpenAPI ツール機能を使用してエージェントを作成する

次の TypeScript コード例は、OpenAPI ツールをツールボックスに追加し、ツールボックスを MCP ツールとしてアタッチすることによって、OpenAPI ツール機能を備えた AI エージェントを作成する方法を示しています。 エージェントは、OpenAPI 仕様で定義されている外部 API を呼び出すことができます。 この例の JavaScript バージョンについては、GitHubの JavaScript リポジトリの Azure SDK の sample を参照してください。

import { DefaultAzureCredential } from "@azure/identity";
import {
  AIProjectClient,
  OpenApiTool,
  OpenApiFunctionDefinition,
  OpenApiAnonymousAuthDetails,
} from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const weatherSpecPath = path.resolve(__dirname, "../assets", "weather_openapi.json");

function loadOpenApiSpec(specPath: string): unknown {
  if (!fs.existsSync(specPath)) {
    throw new Error(`OpenAPI specification not found at: ${specPath}`);
  }

  try {
    const data = fs.readFileSync(specPath, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
  }
}

function createWeatherTool(spec: unknown): OpenApiTool {
  const auth: OpenApiAnonymousAuthDetails = { type: "anonymous" };
  const definition: OpenApiFunctionDefinition = {
    name: "get_weather",
    description: "Retrieve weather information for a location using wttr.in",
    spec,
    auth,
  };

  return {
    type: "openapi",
    openapi: definition,
  };
}

export async function main(): Promise<void> {
  const weatherSpec = loadOpenApiSpec(weatherSpecPath);

  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  const weatherTool = createWeatherTool(weatherSpec);

  console.log("Creating a toolbox with the OpenAPI weather tool...");

  // 1. Add the OpenAPI tool to a toolbox. Using a toolbox is the recommended
  //    way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
  const toolbox = await project.toolboxes.createVersion(
    "openapi-toolbox",
    [weatherTool],
    { description: "Toolbox with the OpenAPI weather tool" },
  );

  // 2. The toolbox exposes an MCP-compatible endpoint.
  const toolboxMcpUrl =
    `${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
    `/versions/${toolbox.version}/mcp?api-version=v1`;

  // 3. Create a remote-tool project connection that points at the toolbox endpoint.
  //    Use a user Entra token so the caller's identity is passed through
  //    (audience https://ai.azure.com). Create the connection once, for example
  //    with the Azure Developer CLI:
  //
  //    azd ai connection create openapi-toolbox-conn \
  //      --kind remote-tool \
  //      --target "<toolboxMcpUrl>" \
  //      --auth-type user-entra-token \
  //      --audience https://ai.azure.com
  const toolboxConnectionName = "openapi-toolbox-conn";

  // 4. Attach the toolbox to a prompt agent as an MCP tool.
  const agent = await project.agents.createVersion("MyOpenApiAgent", {
    kind: "prompt",
    model: "gpt-4.1-mini",
    instructions:
      "You are a helpful assistant that can call external APIs defined by OpenAPI specs to answer user questions.",
    tools: [
      {
        type: "mcp",
        server_label: "toolbox",
        server_url: toolboxMcpUrl,
        require_approval: "never",
        project_connection_id: toolboxConnectionName,
      },
    ],
  });

  // Send a request and stream the response
  const streamResponse = await openai.responses.create(
    {
      input:
        "What's the weather in Seattle and how should I plan my outfit for the day based on the forecast?",
      stream: true,
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        tool_choice: "required",
      },
    },
  );

  // Process the streaming response
  for await (const event of streamResponse) {
    if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "response.output_text.done") {
      console.log("\n");
    }
  }

  // Clean up resources
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

このコードの動作

この TypeScript の例では、匿名認証を使用して気象データ用の OpenAPI ツールを使用してエージェントを作成します。 コードを実行する場合:

  1. ローカル JSON ファイルから天気 OpenAPI 仕様が読み込まれます。
  2. 気象ツールを含むツールボックス バージョンを作成します。
  3. ツールボックスを MCP ツールとしてエージェントにアタッチし、シアトルの天気と衣装の計画について尋ねるストリーミング要求を送信します。
  4. ストリーミング応答を処理し、到着時に差分を表示します。
  5. tool_choice: "required"を使用してツールの使用を強制し、API が確実に呼び出されるようにします。
  6. エージェントを削除してクリーンアップします。

必要な入力

  • インライン文字列値: PROJECT_ENDPOINT(あなたのFoundryプロジェクトエンドポイント)
  • ローカル ファイル: ../assets/weather_openapi.json (OpenAPI 仕様)

予期される出力

Loading OpenAPI specifications from assets directory...
Creating agent with OpenAPI tool...
Agent created (id: asst_abc123, name: MyOpenApiAgent, version: 1)

Sending request to OpenAPI-enabled agent with streaming...
Follow-up response created with ID: resp_xyz789
The weather in Seattle is currently...
Tool call completed: get_weather

Follow-up completed!

Cleaning up resources...
Agent deleted

OpenAPI agent sample completed!

一般的なエラー

  • Error: OpenAPI specification not found: ファイル パスが正しくないか、ファイルがありません
  • AuthenticationError: Azure資格情報が無効です
  • API キーが機能しない: 匿名から API キー認証に切り替える場合は、OpenAPI 仕様が securitySchemes され、 security 正しく構成されていることを確認します

プロジェクト接続で認証された OpenAPI ツールを使用するエージェントを作成する

次の TypeScript コード例は、プロジェクト接続を介して認証された OpenAPI ツールを使用する AI エージェントを作成する方法を示しています。 エージェントは、ローカル資産から TripAdvisor OpenAPI 仕様を読み込み、構成されたプロジェクト接続を介して API を呼び出すことができます。 この例の JavaScript バージョンについては、GitHubの JavaScript リポジトリの Azure SDK の sample を参照してください。

import { DefaultAzureCredential } from "@azure/identity";
import {
  AIProjectClient,
  OpenApiTool,
  OpenApiFunctionDefinition,
  OpenApiProjectConnectionAuthDetails,
} from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const TRIPADVISOR_CONNECTION_ID = "your-tripadvisor-connection-id";
const tripAdvisorSpecPath = path.resolve(__dirname, "../assets", "tripadvisor_openapi.json");

function loadOpenApiSpec(specPath: string): unknown {
  if (!fs.existsSync(specPath)) {
    throw new Error(`OpenAPI specification not found at: ${specPath}`);
  }

  try {
    const data = fs.readFileSync(specPath, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
  }
}

function createTripAdvisorTool(spec: unknown): OpenApiTool {
  const auth: OpenApiProjectConnectionAuthDetails = {
    type: "project_connection",
    security_scheme: {
      project_connection_id: TRIPADVISOR_CONNECTION_ID,
    },
  };

  const definition: OpenApiFunctionDefinition = {
    name: "get_tripadvisor_location_details",
    description:
      "Fetch TripAdvisor location details, reviews, or photos using the Content API via project connection auth.",
    spec,
    auth,
  };

  return {
    type: "openapi",
    openapi: definition,
  };
}

export async function main(): Promise<void> {
  const tripAdvisorSpec = loadOpenApiSpec(tripAdvisorSpecPath);

  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create an agent with the OpenAPI project-connection tool
  const agent = await project.agents.createVersion("MyOpenApiConnectionAgent", {
    kind: "prompt",
    model: "gpt-4.1-mini",
    instructions:
      "You are a travel assistant that consults the TripAdvisor Content API via project connection to answer user questions about locations.",
    tools: [createTripAdvisorTool(tripAdvisorSpec)],
  });

  // Send a request and stream the response
  const streamResponse = await openai.responses.create(
    {
      input:
        "Provide a quick overview of the TripAdvisor location 293919 including its name, rating, and review count.",
      stream: true,
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        tool_choice: "required",
      },
    },
  );

  // Process the streaming response
  for await (const event of streamResponse) {
    if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "response.output_text.done") {
      console.log("\n");
    }
  }

  // Clean up resources
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

このコードの動作

この TypeScript の例では、プロジェクト接続を介した API キー認証で OpenAPI ツールを使用する方法を示します。 コードを実行する場合:

  1. ローカル ファイルから TripAdvisor OpenAPI 仕様を読み込みます。
  2. TRIPADVISOR_CONNECTION_ID定数を使用して認証を構成します。
  3. API キー認証にプロジェクト接続を使用する TripAdvisor ツールを使用してエージェントを作成します。
  4. TripAdvisor の場所の詳細に対するストリーミング要求を送信します。
  5. tool_choice: "required"を使用してツールの使用を強制し、API が確実に呼び出されるようにします。
  6. ストリーミング応答を処理して表示します。
  7. エージェントを削除してクリーンアップします。

必要な入力

  • インライン文字列値: PROJECT_ENDPOINTTRIPADVISOR_CONNECTION_ID
  • ローカル ファイル: ../assets/tripadvisor_openapi.json
  • TripAdvisor API キーで設定されたプロジェクト接続

予期される出力

Loading TripAdvisor OpenAPI specification from assets directory...
Creating agent with OpenAPI project-connection tool...
Agent created (id: asst_abc123, name: MyOpenApiConnectionAgent, version: 1)

Sending request to TripAdvisor OpenAPI agent with streaming...
Follow-up response created with ID: resp_xyz789
Location 293919 is the Eiffel Tower in Paris, France. It has a rating of 4.5 stars with over 140,000 reviews...
Tool call completed: get_tripadvisor_location_details

Follow-up completed!

Cleaning up resources...
Agent deleted

TripAdvisor OpenAPI agent sample completed!

一般的なエラー

  • Error: OpenAPI specification not found: ファイル パスを確認します。
  • 接続が見つかりません: TRIPADVISOR_CONNECTION_ID が正しく、接続が存在するかどうかを確認します。
  • AuthenticationException: プロジェクト接続の API キーが無効です。
  • API キーが要求に挿入されない: OpenAPI 仕様には、適切な securitySchemes ( componentsの下) と security セクションが含まれている必要があります。 securitySchemesのキー名は、プロジェクト接続のキーと一致している必要があります。
  • Content type is not supported: 現在サポートされている要求本文のコンテンツ タイプは、 application/jsonapplication/json-patch+jsonの 2 つだけです。 応答コンテンツ タイプは制限されません。

セキュリティとデータに関する考慮事項

エージェントを OpenAPI ツールに接続すると、エージェントはユーザー入力から派生した要求パラメーターをターゲット API に送信できます。

  • シークレット (API キーとトークン) にはプロジェクト接続を使用します。 OpenAPI 仕様ファイルまたはソース コードにシークレットを配置しないでください。
  • 運用環境でツールを使用する前に、API が受け取るデータと返されるデータを確認します。
  • 最小特権アクセスを使用します。 マネージド ID の場合は、ターゲット サービスに必要なロールのみを割り当てます。

API キーを使用して認証する

ヘッダーまたはクエリ パラメーターにキーが必要な API には、このバリアントを使用します。 OpenAPI ツールごとに使用できる API キー セキュリティ スキームは 1 つだけです。 API に複数のセキュリティ スキームが必要な場合は、複数の OpenAPI ツールを作成します。

  1. OpenAPI 仕様のセキュリティ スキーマを更新します。 これには、 securitySchemes セクションと、 apiKey型の 1 つのスキームがあります。 例えば:

     "securitySchemes": {
         "apiKeyHeader": {
                 "type": "apiKey",
                 "name": "x-api-key",
                 "in": "header"
             }
     }
    

    通常は、接続内のnameの名前に対応するkey フィールドのみを更新する必要があります。 セキュリティ スキームに複数のスキームが含まれている場合は、そのうちの 1 つだけを保持します。

  2. security セクションを含むように OpenAPI 仕様を更新します。

    "security": [
         {  
         "apiKeyHeader": []  
         }  
     ]
    
  3. この記事で後述するように、API キーが格納され、接続経由で渡されるため、API キーが必要な OpenAPI 仕様のパラメーターを削除します。

  4. API キーを格納する接続を作成します。

  5. Foundry ポータルに移動し、プロジェクトを開きます。

  6. シークレットを格納する接続を作成または選択します。 プロジェクトへの新しい接続の追加を参照してください

    メモ

    後で API キーを再生成する場合は、新しいキーで接続を更新する必要があります。

  7. 次の情報を入力します

    • key: セキュリティ スキームの name フィールド。 この例では、次のようになります。 x-api-key

             "securitySchemes": {
                "apiKeyHeader": {
                          "type": "apiKey",
                          "name": "x-api-key",
                          "in": "header"
                      }
              }
      
    • 値: YOUR_API_KEY

  8. 接続を作成した後は、SDK または REST API を使用して接続を使用できます。 この記事の上部にあるタブを使用して、コード例を確認します。

ベアラー トークン接続を設定する

このバリアントは、 Authorization ヘッダーにベアラー トークンが必要な API に使用します。 API キー認証と同じ project_connection 認証の種類を使用しますが、OpenAPI のセキュリティスキームと接続の値は異なります。

OpenAPI 仕様は次のようになります。

  BearerAuth:
    type: http
    scheme: bearer
    bearerFormat: JWT

次の手順を実行する必要があります。

  1. ヘッダー名としてsecuritySchemesを使用するように OpenAPI 仕様のAuthorizationを更新します。

    "securitySchemes": {
        "bearerAuth": {
            "type": "apiKey",
            "name": "Authorization",
            "in": "header"
        }
    }
    
  2. スキームを参照する security セクションを追加します。

    "security": [
        {
            "bearerAuth": []
        }
    ]
    
  3. Foundry プロジェクトで カスタム キー 接続を作成します。

    1. Foundry ポータルに移動し、プロジェクトを開きます。
    2. シークレットを格納する接続を作成または選択します。 プロジェクトへの新しい接続の追加を参照してください
    3. 次の値を入力します。
      • key: Authorization (namesecuritySchemes フィールドと一致する必要があります)
      • value: Bearer <token> ( <token> を実際のトークンに置き換えます)

    重要

値には、トークンの前にスペースが続く Bearer 単語を含める必要があります。 例: Bearer eyJhbGciOiJSUzI1NiIs...Bearer プレフィックスと次の領域を省略すると、API は必要な承認スキーム プレフィックスなしで未加工のトークンを受け取り、要求は失敗します。

  1. 接続を作成したら、API キー認証の場合と同じ方法で、コード内の project_connection 認証の種類で接続を使用します。 接続 ID は、/subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}} と同じ形式を使用します。

マネージド ID を使用した認証 (Microsoft Entra ID)

Microsoft Entra ID は、従業員が外部リソースへのアクセスに使用できるクラウドベースの ID およびアクセス管理サービスです。 Microsoft Entra IDを使用すると、API キーを使用しなくても、API にセキュリティを強化できます。 マネージド ID 認証を設定すると、エージェントは使用する Foundry ツールを使用して認証を行います。

重要

マネージド ID 認証は、ターゲット サービスがMicrosoft Entra IDトークンを受け入れる場合にのみ機能します。 ターゲット API がMicrosoft Entra IDをサポートしていないカスタム認証スキームを使用する場合は、代わりに API キー または Bearer トークン 認証を使用します。

対象ユーザー URI を理解する

audienceresource 識別子 または Application ID URI とも呼ばれる)は、トークンがどのサービスや API にアクセスするかを Microsoft Entra ID に通知します。 対象ユーザーの値は、ターゲット サービスが想定しているものと一致する必要があります。または、認証が失敗し、401 エラーが発生します。

メモ

対象ユーザーは Foundry プロジェクト エンドポイント ではありません 。 これは、OpenAPI ツールが呼び出すターゲット サービスのリソース識別子です。

次の表に、一般的なAzure サービスの対象ユーザー URI を示します。

ターゲット サービス 対象ユーザー URI
Azure Storage https://storage.azure.com
Azure Key Vault https://vault.azure.net
Azure AI 検索 https://search.azure.com
Azure Logic Apps https://logic.azure.com
Azure API Management (管理プレーン) https://management.azure.com
Microsoft Entra アプリの登録によって保護された API (OAuth を使用した APIM を含む) アプリの登録からの アプリケーション ID URI (たとえば、 api://<client-id>)

ヒント

Azure API Managementを使用して OAuth 2.0 検証ポリシーを使用してカスタム API を保護する場合、対象ユーザーは API を保護するアプリ登録から Application ID URI になります (https://management.azure.comではありません)。 管理プレーン対象ユーザーは、APIM リソース自体に対するAzure Resource Manager操作にのみ適用されます。

エージェントがMicrosoft Entra IDを使用して認証する方法の詳細については、「Agent の ID と認証を参照してください。

対象ユーザーを検索して確認する

次の手順を使用して、適切な対象ユーザーの値を確認します。

  • Azure サービスの場合: サービスのドキュメントでMicrosoft Entra IDリソース識別子を確認します。 ほとんどのAzure サービスでは、認証ドキュメントに対象ユーザー URI が一覧表示されます。
  • Microsoft Entra アプリの登録によって保護される API: Azure ポータルで、 Microsoft Entra ID>アプリの登録> に移動> API を公開するを選択します。 ページの上部にある アプリケーション ID URI は、対象ユーザーの値です。
  • トークンの対象ユーザーを確認するには: https://jwt.ms でアクセス トークンをデコードし、 aud 要求を確認します。 aud値は、ターゲット サービスが期待する対象ユーザーと一致する必要があります。

マネージド ID 認証を設定する

マネージド ID を使用して認証を設定するには:

  1. Foundry リソースでシステム割り当てマネージド ID が有効になっていることを確認します。

システム割り当てマネージド ID の設定を示すAzure ポータルのスクリーンショット。

  1. OpenAPI 仕様を使用して接続するサービスのリソースを作成します。

  2. リソースへの適切なアクセス権を割り当てます。

    1. リソースのAccess Controlを選択してください。

    2. [ 追加] を選択し、画面の上部にある ロールの割り当てを追加 します。

      [ロールの割り当ての追加] アクションを示すAzure ポータルのスクリーンショット。

  3. OpenAPI 仕様で操作を許可する最小特権のデータ プレーンまたはアプリケーション ロールを選択します。 Azure Resource Manager閲覧者アクセスだけでは、データ プレーン アクセスは許可されません。 次へを選択します。

  4. [ マネージド ID] を 選択し、[ メンバーの選択] を選択します。

  5. マネージド ID ドロップダウン メニューで Foundry アカウント を検索し、エージェントの Foundry アカウントを選択します。

  6. [完了] を選択します

  7. セットアップが完了したら、Foundry ポータル、SDK、または REST API からツールを使用して続行できます。 この記事の上部にあるタブを使用して、コード サンプルを確認します。

一般的なエラーのトラブルシューティング

症状 考えられる原因 解決方法
API キーは要求に含まれません。 securitySchemesセクションまたはsecurityセクションがない OpenAPI 仕様。 OpenAPI 仕様に、 components.securitySchemes と最上位レベルの security セクションの両方が含まれていることを確認します。 スキーム name がプロジェクト接続のキー名と一致していることを確認します。
エージェントは OpenAPI ツールを呼び出しません。 ツールの選択が設定されていないか、説明的でない operationId tool_choice="required"を使用して、ツールの呼び出しを強制します。 モデルが適切な操作を選択できるように、 operationId 値がわかりやすいことを確認します。
マネージド ID の認証は失敗します。 マネージド ID が有効になっていないか、ロールの割り当てが不足しています。 Foundry リソースでシステム割り当てマネージド ID を有効にします。 OpenAPI 仕様の操作に、ターゲット サービスの最小特権データ プレーンまたはアプリケーション ロールを割り当てます。
マネージド ID は、ロールが割り当てられている場合でも 401 を返します。 対象ユーザー URI が、ターゲット サービスで想定されているものと一致しません。 対象ユーザー URI がターゲット サービスのリソース識別子と一致するかどうかを確認します。 Azureサービスについては、サービスのドキュメントを参照してください。 Microsoft Entra保護された API の場合は、アプリ登録のアプリケーション ID URI を使用します。 https://jwt.msでトークンをデコードし、aud要求の一致を確認します。 対象 ユーザー URI を理解するを参照してください。
ターゲット API によって拒否されたマネージド ID トークン。 ターゲット サービスでは、Microsoft Entra ID トークンを受け入れられません。 ターゲット サービスでMicrosoft Entra ID認証がサポートされたことを確認します。 そうでない場合は、代わりに API キーまたはベアラー トークン認証を使用します。
リクエストが 400 Bad Request で失敗しました。 OpenAPI 仕様が実際の API と一致しません。 実際の API に対して OpenAPI 仕様を検証します。 パラメーター名、型、および必須フィールドを確認します。
要求は 401 Unauthorized で失敗します。 API キーまたはトークンが無効であるか、有効期限が切れています。 API キー/トークンを再生成し、プロジェクト接続を更新します。 接続 ID が正しいことを確認します。
ツールは予期しない応答形式を返します。 応答スキーマが OpenAPI 仕様で定義されていません。 モデルの理解を深めるために、OpenAPI 仕様に応答スキーマを追加します。
operationId 検証エラー。 operationIdの文字が無効です。 -値には、文字、_、およびoperationIdのみを使用します。 数字と特殊文字を削除します。
接続が見つかりませんエラー。 接続名または ID が一致しません。 OPENAPI_PROJECT_CONNECTION_NAMEが Foundry プロジェクトの接続名と一致するかどうかを確認します。
ベアラー トークンが正しく送信されませんでした。 接続値に、 Bearer プレフィックスと次のスペースがありません。 接続値を Bearer <token> に設定します ( Bearer という単語とトークンの前にスペースを付けます)。 OpenAPI 仕様 securitySchemes"name": "Authorization" を使用していることを確認します。

認証方法を選択する

次の表は、OpenAPI ツールに適した認証方法を選択するのに役立ちます。

認証方法 最適な用途 セットアップの複雑さ
匿名 認証なしのパブリック API
API キー キーベースのアクセス権を持つ非Microsoft API 中くらい
マネージド ID Azure サービスとMicrosoft Entra IDで保護されたAPI。 ターゲット サービスは、Microsoft Entra ID トークンを受け入れ、Azure RBAC または Microsoft Entra ベースのアクセス制御をサポートする必要があります。 中高レベル