Microsoft Agent Framework では、 GitHub Copilot SDK をバックエンドとして使用するエージェントの作成がサポートされています。 GitHub Copilot エージェントは、シェル コマンドの実行、ファイル操作、URL フェッチ、モデル コンテキスト プロトコル (MCP) サーバー統合など、強力なコーディング指向の AI 機能にアクセスできます。
Important
GitHub Copilot エージェントでは、GitHub Copilot CLI をインストールして認証する必要があります。 セキュリティのために、コンテナー化された環境 (Docker/Dev Container) でシェルまたはファイルのアクセス許可を持つエージェントを実行することをお勧めします。
はじめに
必要な NuGet パッケージをプロジェクトに追加します。
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
GitHub Copilot エージェントを作成する
最初の手順として、 CopilotClient を作成して開始します。 次に、 AsAIAgent 拡張メソッドを使用してエージェントを作成します。
using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
AIAgent agent = copilotClient.AsAIAgent();
Console.WriteLine(await agent.RunAsync("What is Microsoft Agent Framework?"));
ツールと指示書を使って
エージェントを作成するときに、関数ツールとカスタム命令を指定できます。
using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
AIFunction weatherTool = AIFunctionFactory.Create((string location) =>
{
return $"The weather in {location} is sunny with a high of 25C.";
}, "GetWeather", "Get the weather for a given location.");
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
AIAgent agent = copilotClient.AsAIAgent(
tools: [weatherTool],
instructions: "You are a helpful weather agent.");
Console.WriteLine(await agent.RunAsync("What's the weather like in Seattle?"));
エージェントの機能
ストリーミング応答
応答が生成され次第取得します。
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
AIAgent agent = copilotClient.AsAIAgent();
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a short story."))
{
Console.Write(update);
}
Console.WriteLine();
セッションの管理
セッションを使用して複数の対話間で会話コンテキストを維持する:
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
await using GitHubCopilotAgent agent = new(
copilotClient,
instructions: "You are a helpful assistant. Keep your answers short.");
AgentSession session = await agent.CreateSessionAsync();
// First turn
await agent.RunAsync("My name is Alice.", session);
// Second turn - agent remembers the context
AgentResponse response = await agent.RunAsync("What is my name?", session);
Console.WriteLine(response); // Should mention "Alice"
Permissions
既定では、エージェントはシェル コマンド、ファイルの読み取り/書き込み、または URL のフェッチを実行できません。 これらの機能を有効にするには、 SessionConfigを使用してアクセス許可ハンドラーを指定します。
static Task<PermissionRequestResult> PromptPermission(
PermissionRequest request, PermissionInvocation invocation)
{
Console.WriteLine($"\n[Permission Request: {request.Kind}]");
Console.Write("Approve? (y/n): ");
string? input = Console.ReadLine()?.Trim().ToUpperInvariant();
string kind = input is "Y" or "YES" ? "approved" : "denied-interactively-by-user";
return Task.FromResult(new PermissionRequestResult { Kind = kind });
}
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
SessionConfig sessionConfig = new()
{
OnPermissionRequest = PromptPermission,
};
AIAgent agent = copilotClient.AsAIAgent(sessionConfig);
Console.WriteLine(await agent.RunAsync("List all files in the current directory"));
MCP サーバー
拡張機能のためにローカル (stdio) またはリモート (HTTP) MCP サーバーに接続します。
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
SessionConfig sessionConfig = new()
{
OnPermissionRequest = PromptPermission,
McpServers = new Dictionary<string, object>
{
// Local stdio server
["filesystem"] = new McpLocalServerConfig
{
Type = "stdio",
Command = "npx",
Args = ["-y", "@modelcontextprotocol/server-filesystem", "."],
Tools = ["*"],
},
// Remote HTTP server
["microsoft-learn"] = new McpRemoteServerConfig
{
Type = "http",
Url = "https://learn.microsoft.com/api/mcp",
Tools = ["*"],
},
},
};
AIAgent agent = copilotClient.AsAIAgent(sessionConfig);
Console.WriteLine(await agent.RunAsync("Search Microsoft Learn for 'Azure Functions' and summarize the top result"));
ヒント
実行可能な完全な例については、 .NET サンプル を参照してください。
エージェントの使用
エージェントは標準の AIAgent であり、すべての標準 AIAgent 操作をサポートします。
エージェントを実行して操作する方法の詳細については、 エージェントの概要に関するチュートリアルを参照してください。
[前提条件]
Microsoft Agent Framework GitHub Copilot パッケージをインストールします。
pip install agent-framework-github-copilot --pre
コンフィギュレーション
必要に応じて、次の環境変数を使用してエージェントを構成できます。
| Variable | Description |
|---|---|
GITHUB_COPILOT_CLI_PATH |
Copilot CLI 実行可能ファイルへのパス |
GITHUB_COPILOT_MODEL |
使用するモデル (例: gpt-5、 claude-sonnet-4) |
GITHUB_COPILOT_TIMEOUT |
要求タイムアウト (秒単位) |
GITHUB_COPILOT_LOG_LEVEL |
CLI ログ レベル |
はじめに
Agent Framework から必要なクラスをインポートします。
import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
GitHub Copilot エージェントを作成する
基本的なエージェントの作成
GitHub Copilot エージェントを作成する最も簡単な方法は次のとおりです。
async def basic_example():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful assistant."},
)
async with agent:
result = await agent.run("What is Microsoft Agent Framework?")
print(result)
明示的な構成を使用する
default_optionsを使用して明示的な構成を指定できます。
async def explicit_config_example():
agent = GitHubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant.",
"model": "gpt-5",
"timeout": 120,
},
)
async with agent:
result = await agent.run("What can you do?")
print(result)
エージェントの機能
関数ツール
エージェントにカスタム関数を装備します。
from typing import Annotated
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny with a high of 25C."
async def tools_example():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent:
result = await agent.run("What's the weather like in Seattle?")
print(result)
ストリーミング応答
ユーザー エクスペリエンスを向上するために生成された応答を取得します。
async def streaming_example():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful assistant."},
)
async with agent:
print("Agent: ", end="", flush=True)
async for chunk in agent.run("Tell me a short story.", stream=True):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
スレッド管理
複数の対話間で会話コンテキストを維持する:
async def thread_example():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful assistant."},
)
async with agent:
thread = agent.create_session()
# First interaction
result1 = await agent.run("My name is Alice.", session=thread)
print(f"Agent: {result1}")
# Second interaction - agent remembers the context
result2 = await agent.run("What's my name?", session=thread)
print(f"Agent: {result2}") # Should remember "Alice"
Permissions
既定では、エージェントはシェル コマンド、ファイルの読み取り/書き込み、または URL のフェッチを実行できません。 これらの機能を有効にするには、アクセス許可ハンドラーを指定します。
from copilot.types import PermissionRequest, PermissionRequestResult
def prompt_permission(
request: PermissionRequest, context: dict[str, str]
) -> PermissionRequestResult:
kind = request.get("kind", "unknown")
print(f"\n[Permission Request: {kind}]")
response = input("Approve? (y/n): ").strip().lower()
if response in ("y", "yes"):
return PermissionRequestResult(kind="approved")
return PermissionRequestResult(kind="denied-interactively-by-user")
async def permissions_example():
agent = GitHubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant that can execute shell commands.",
"on_permission_request": prompt_permission,
},
)
async with agent:
result = await agent.run("List the Python files in the current directory")
print(result)
MCP サーバー
拡張機能のためにローカル (stdio) またはリモート (HTTP) MCP サーバーに接続します。
from copilot.types import MCPServerConfig
async def mcp_example():
mcp_servers: dict[str, MCPServerConfig] = {
# Local stdio server
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
"tools": ["*"],
},
# Remote HTTP server
"microsoft-learn": {
"type": "http",
"url": "https://learn.microsoft.com/api/mcp",
"tools": ["*"],
},
}
agent = GitHubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant with access to the filesystem and Microsoft Learn.",
"on_permission_request": prompt_permission,
"mcp_servers": mcp_servers,
},
)
async with agent:
result = await agent.run("Search Microsoft Learn for 'Azure Functions' and summarize the top result")
print(result)
エージェントの使用
エージェントは標準の BaseAgent であり、すべての標準エージェント操作をサポートします。
エージェントを実行して操作する方法の詳細については、 エージェントの概要に関するチュートリアルを参照してください。