このガイドでは、Azure リソースと対話するために Azure Model Context Protocol (MCP) ツールを使用するように GitHub Copilot SDK を構成する方法について説明します。
Azure MCP には、AI アシスタントが Azure リソースと直接やり取りできるようにする一連のツールが用意されています。 Copilot SDK と統合すると、自然言語を利用して Azure サブスクリプション、リソース グループ、ストレージ アカウントなどを管理するアプリケーションを構築できます。
[前提条件]
ローカル開発のために Azure MCP Server にサインインする
Azure MCP Server は、.NET 用 Azure ID ライブラリを使用して Microsoft Entra ID に対して認証を行います。 サーバーでは、 次の 2 つの認証モードがサポートされています。
-
ブローカー モード:
InteractiveBrowserCredentialでオペレーティング システムのネイティブ認証 (Windows Web アカウント マネージャーなど) を使用します。
-
資格情報チェーン モード: 環境変数、Visual Studio Code、Visual Studio、Azure CLI、Azure PowerShell、Azure Developer CLI、対話型ブラウザー認証など、複数の認証方法を順番に試行します。
次のいずれかの方法を使用してサインインします。
- コマンド パレットを開きます (Mac の
Ctrl+Shift+P または Cmd+Shift+P )。
-
Azure を実行する: サインインし、指示に従います。
- [ ファイル > アカウント設定] に移動します。
- [ アカウントの追加] を 選択し、画面の指示に従います。
サインイン後、Azure MCP Server は、アクセス許可に基づいて Azure サービスに対する操作を認証して実行できます。
Azure MCP サーバーの構成例
使用するプログラミング SDK に関係なく、ツールを使用できるように Azure MCP サーバーをアプリ コンテキストで構成する必要があります。 重要な構成は次のようになります。
{
"mcp_servers": {
"azure-mcp": {
"type": "local",
"command": "npx",
"args": ["-y", "@azure/mcp@latest", "server", "start"],
"tools": ["*"]
}
}
}
tools: ["*"] パラメーターは必須です。MCP サーバーからのすべてのツールをセッションに対して有効にします。
統合の例
次の例は、さまざまな言語で SDK を統合する方法を示しています。
注
起動を高速化するために、 npm install -g @azure/mcp@latestを使用して Azure MCP Server をグローバルにインストールできます。
インストール作業
pip を使用して Python SDK パッケージをインストールします。
pip install github-copilot-sdk
サンプル コード
次のコードは、完全なフローを示しています。
import asyncio
from copilot import CopilotClient
from copilot.generated.session_events import SessionEventType
async def main():
# Initialize the Copilot client
client = CopilotClient({
"cli_args": [
"--allow-all-tools",
"--allow-all-paths",
]
})
await client.start()
# Configure Azure MCP server in session config
azure_mcp_config = {
"azure-mcp": {
"type": "local",
"command": "npx",
"args": ["-y", "@azure/mcp@latest", "server", "start"],
"tools": ["*"], # Enable all Azure MCP tools
}
}
# Create session with MCP servers
session = await client.create_session({
"model": "gpt-4.1", # Default model; BYOK can override
"streaming": True,
"mcp_servers": azure_mcp_config,
})
# Handle events
def handle_event(event):
if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
if hasattr(event.data, 'delta_content') and event.data.delta_content:
print(event.data.delta_content, end="", flush=True)
elif event.type == SessionEventType.TOOL_EXECUTION_START:
tool_name = getattr(event.data, 'tool_name', 'unknown')
print(f"\n[TOOL: {tool_name}]")
session.on(handle_event)
# Send prompt
await session.send_and_wait({
"prompt": "List all resource groups in my Azure subscription"
})
await client.stop()
if __name__ == "__main__":
asyncio.run(main())
前述のコード:
- Copilot クライアントを初期化します。
-
npxを使用して Azure MCP サーバーを構成します。
- GPT-4.1 モデルを使用してセッションを作成し、ストリーミングを有効にします。
- アシスタントの応答とツール実行ログを出力するイベントを処理します。
- Azure リソース グループを一覧表示するプロンプトを送信します。
インストール作業
npm を使用して Node.js SDK パッケージをインストールします。
npm install @github/copilot-sdk
次のコードは、完全なフローを示しています。
import { CopilotClient } from '@github/copilot-sdk';
import type { MCPLocalServerConfig } from '@github/copilot-sdk';
async function main() {
// Initialize the Copilot client
const client = new CopilotClient({
cliArgs: [
'--allow-all-tools',
'--allow-all-paths',
]
});
await client.start();
// Configure Azure MCP server in session config
const azureMcpConfig: Record<string, MCPLocalServerConfig> = {
'azure-mcp': {
type: 'local',
command: 'npx',
args: ['-y', '@azure/mcp@latest', 'server', 'start'],
tools: ['*'], // Enable all Azure MCP tools
}
};
// Create session with MCP servers
const session = await client.createSession({
model: 'gpt-4.1', // Default model; BYOK can override
streaming: true,
mcpServers: azureMcpConfig,
});
// Handle events
session.on((event) => {
if (event.type === 'assistant.message_delta') {
if (event.data?.deltaContent) {
process.stdout.write(event.data.deltaContent);
}
} else if (event.type === 'tool.execution_start') {
const toolName = event.data?.toolName || 'unknown';
console.log(`\n[TOOL: ${toolName}]`);
}
});
// Send prompt
await session.sendAndWait({
prompt: 'List all resource groups in my Azure subscription 16caa5c4-46f1-4bfd-8c1b-a99f1efc8845'
});
await client.stop();
}
main().catch(console.error);
前述のコード:
- Copilot クライアントを初期化します。
-
npxを使用して Azure MCP サーバーを構成します。
- GPT-4.1 モデルを使用してセッションを作成し、ストリーミングを有効にします。
- アシスタントの応答とツール実行ログを出力するイベントを処理します。
- Azure リソース グループを一覧表示するプロンプトを送信します。
インストール作業
NuGet パッケージの内容をプロジェクトに追加します。
dotnet add package GitHub.Copilot.SDK
サンプル コード
次の C# コードは、完全なフローを示しています。
using GitHub.Copilot.SDK;
// Initialize the Copilot client
await using var client = new CopilotClient(new CopilotClientOptions
{
CliArgs = new[] { "--allow-all-tools", "--allow-all-paths" }
});
await client.StartAsync();
// Configure Azure MCP server in session config
var mcpServers = new Dictionary<string, object>
{
["azure-mcp"] = new McpLocalServerConfig
{
Type = "local",
Command = "npx",
Args = ["-y", "@azure/mcp@latest", "server", "start"],
Tools = ["*"] // Enable all Azure MCP tools
}
};
// Create session with MCP servers
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-4.1", // Default model; BYOK can override
Streaming = true,
McpServers = mcpServers
});
// Handle events
session.On(evt =>
{
if (evt is AssistantMessageDeltaEvent delta)
{
if (!string.IsNullOrEmpty(delta.Data.DeltaContent))
{
Console.Write(delta.Data.DeltaContent);
}
}
else if (evt is ToolExecutionStartEvent toolStart)
{
Console.WriteLine($"\n[TOOL: {toolStart.Data.ToolName}]");
}
});
// Send prompt
await session.SendAndWaitAsync(new MessageOptions
{
Prompt = "List all resource groups in my Azure subscription"
});
前述のコード:
- Copilot クライアントを初期化します。
-
npxを使用して Azure MCP サーバーを構成します。
- GPT-4.1 モデルを使用してセッションを作成し、ストリーミングを有効にします。
- アシスタントの応答とツール実行ログを出力するイベントを処理します。
- Azure リソース グループを一覧表示するプロンプトを送信します。
インストール作業
go getを使用して Go SDK パッケージを取得します。
go get github.com/github/copilot-sdk/go
サンプル コード
次のコードは、完全なフローを示しています。
package main
import (
"context"
"fmt"
"log"
copilot "github.com/github/copilot-sdk/go"
)
func main() {
ctx := context.Background()
// Initialize the Copilot client
client, err := copilot.NewClient(copilot.ClientOptions{
CLIArgs: []string{
"--allow-all-tools",
"--allow-all-paths",
},
})
if err != nil {
log.Fatal(err)
}
if err := client.Start(ctx); err != nil {
log.Fatal(err)
}
defer client.Stop(ctx)
// Configure Azure MCP server in session config
azureMcpConfig := map[string]copilot.MCPServerConfig{
"azure-mcp": {
Type: "local",
Command: "npx",
Args: []string{"-y", "@azure/mcp@latest", "server", "start"},
Tools: []string{"*"}, // Enable all Azure MCP tools
},
}
// Create session with MCP servers
session, err := client.CreateSession(ctx, copilot.SessionConfig{
Model: "gpt-4.1", // Default model; BYOK can override
Streaming: true,
MCPServers: azureMcpConfig,
})
if err != nil {
log.Fatal(err)
}
// Handle events
session.OnEvent(func(event copilot.SessionEvent) {
switch event.Type {
case copilot.AssistantMessageDelta:
if event.Data.DeltaContent != "" {
fmt.Print(event.Data.DeltaContent)
}
case copilot.ToolExecutionStart:
fmt.Printf("\n[TOOL: %s]\n", event.Data.ToolName)
}
})
// Send prompt
err = session.SendAndWait(ctx, copilot.Message{
Prompt: "List all resource groups in my Azure subscription",
})
if err != nil {
log.Fatal(err)
}
}
前述のコード:
- Copilot クライアントを初期化します。
-
npxを使用して Azure MCP サーバーを構成します。
- GPT-4.1 モデルを使用してセッションを作成し、ストリーミングを有効にします。
- アシスタントの応答とツール実行ログを出力するイベントを処理します。
- Azure リソース グループを一覧表示するプロンプトを送信します。