[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ADCF7VPC5ZM2CNCKRJJDS9":3,"skill-same:01M6ADCF7VPC5ZM2CNCKRJJDS9":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":46,"linkOnly":47,"markdownContent":48,"markdownBody":49,"frontMatter":50,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":54,"repositoryHtmlUrl":55,"repositoryHomepageUrl":56,"ownerHtmlUrl":57,"ownerBlogUrl":58,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6ADCF7VPC5ZM2CNCKRJJDS9","copilot-sdk",null,"Build agentic applications with the Microsoft Copilot SDK, transitioning from GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, Microsoft Copilot SDK, GitHub Copilot SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.","github\u002Fawesome-copilot","github","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F9919?v=4","01M6AC83DS133TPXFSP1DHNCC6","GitHub","01M6AD3PBDYPK7NVFJNJ66Y8RS",41081,"MIT","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fcopilot-sdk\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45],"sdk","copilot sdk","copilot","when","implementing","use","triggers","applications","Tools","microsoft copilot","apps","embedding","app","server","streaming","ai agents","mcp server","agentic","MCP","sessions","custom agents","github copilot","2026-11-10 10:12:30",false,"---\nname: copilot-sdk\ndescription: Build agentic applications with the Microsoft Copilot SDK, transitioning from GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, Microsoft Copilot SDK, GitHub Copilot SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.\n---\n\n# Microsoft Copilot SDK\n\nEmbed Copilot's agentic workflows in any application using Python, TypeScript, Go, or .NET.\n\n## Overview\n\nThe Microsoft Copilot SDK is transitioning from the GitHub Copilot SDK. It is becoming the programmable interface for the Microsoft Copilot harness, the shared agent foundation used across Microsoft and GitHub products. This transition is happening in phases, and no immediate changes are required for existing users. Package names, namespaces, and some documentation may continue to use GitHub branding during the transition.\n\nThis guide keeps the currently published package names and imports in its examples. Follow the [official transition announcement](https:\u002F\u002Fgithub.blog\u002Fchangelog\u002F2026-10-28-github-copilot-sdk-is-becoming-microsoft-copilot-sdk\u002F) for migration updates.\n\nThe SDK provides a production-tested agent runtime you can invoke programmatically. You define agent behavior, while Copilot handles planning, tool invocation, file edits, and more.\n\n## Prerequisites\n\n1. **GitHub Copilot access** and an authenticated environment\n2. **Language runtime**: Node.js ^20.19.0 or >=22.12.0, Python 3.11+, Go 1.24+, or a .NET Standard 2.0-compatible implementation\n3. **Go**: GitHub Copilot CLI installed and authenticated ([Installation guide](https:\u002F\u002Fdocs.github.com\u002Fen\u002Fcopilot\u002Fhow-tos\u002Fset-up\u002Finstall-copilot-cli))\n\nThe TypeScript, Python, and .NET packages use a bundled Copilot runtime by default, so they do not need a separate CLI installation.\n\n## Installation\n\n### Node.js\u002FTypeScript\n```bash\nmkdir copilot-demo && cd copilot-demo\nnpm init -y --init-type module\nnpm install @github\u002Fcopilot-sdk tsx\n```\n\n### Python\n```bash\npip install github-copilot-sdk\n\n# Optional: pre-download the bundled runtime instead of downloading it on first use\npython -m copilot download-runtime\n```\n\nPublished Python wheels include a pinned runtime version. The pre-download command caches that runtime locally; if skipped, the SDK attempts to download it automatically on first use.\n\n### Go\n```bash\nmkdir copilot-demo && cd copilot-demo\ngo mod init copilot-demo\ngo get github.com\u002Fgithub\u002Fcopilot-sdk\u002Fgo\n```\n\n### .NET\n```bash\ndotnet new console -n CopilotDemo && cd CopilotDemo\ndotnet add package GitHub.Copilot.SDK\n```\n\n## Quick Start\n\n### TypeScript\n```typescript\nimport { CopilotClient, approveAll } from \"@github\u002Fcopilot-sdk\";\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n});\n\nconst response = await session.sendAndWait({ prompt: \"What is 2 + 2?\" });\nconsole.log(response?.data.content);\n\nawait client.stop();\nprocess.exit(0);\n```\n\nRun: `npx tsx index.ts`\n\n### Python\n```python\nimport asyncio\nfrom copilot import CopilotClient, PermissionHandler\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n        ) as session:\n            response = await session.send_and_wait(\"What is 2 + 2?\")\n            print(response.data.content)\n\nasyncio.run(main())\n```\n\n### Go\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    copilot \"github.com\u002Fgithub\u002Fcopilot-sdk\u002Fgo\"\n)\n\nfunc main() {\n    client := copilot.NewClient(nil)\n    if err := client.Start(); err != nil {\n        log.Fatal(err)\n    }\n    defer client.Stop()\n\n    session, err := client.CreateSession(&copilot.SessionConfig{\n        OnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n        Model:               \"gpt-4.1\",\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    response, err := session.SendAndWait(copilot.MessageOptions{Prompt: \"What is 2 + 2?\"}, 0)\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Println(*response.Data.Content)\n    os.Exit(0)\n}\n```\n\n### .NET (C#)\n```csharp\nusing GitHub.Copilot.SDK;\n\nawait using var client = new CopilotClient();\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n});\n\nvar response = await session.SendAndWaitAsync(new MessageOptions { Prompt = \"What is 2 + 2?\" });\nConsole.WriteLine(response?.Data.Content);\n```\n\nRun: `dotnet run`\n\n## Streaming Responses\n\nEnable real-time output for better UX:\n\n### TypeScript\n```typescript\nimport { CopilotClient, approveAll, SessionEvent } from \"@github\u002Fcopilot-sdk\";\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    streaming: true,\n});\n\nsession.on((event: SessionEvent) => {\n    if (event.type === \"assistant.message_delta\") {\n        process.stdout.write(event.data.deltaContent);\n    }\n    if (event.type === \"session.idle\") {\n        console.log(); \u002F\u002F New line when done\n    }\n});\n\nawait session.sendAndWait({ prompt: \"Tell me a short joke\" });\n\nawait client.stop();\nprocess.exit(0);\n```\n\n### Python\n```python\nimport asyncio\nimport sys\nfrom copilot import CopilotClient, PermissionHandler\nfrom copilot.generated.session_events import SessionEventType\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n            streaming=True,\n        ) as session:\n            def handle_event(event):\n                if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:\n                    sys.stdout.write(event.data.delta_content)\n                    sys.stdout.flush()\n                if event.type == SessionEventType.SESSION_IDLE:\n                    print()\n\n            session.on(handle_event)\n            await session.send_and_wait(\"Tell me a short joke\")\n\nasyncio.run(main())\n```\n\n### Go\n```go\nsession, err := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n    Model:     \"gpt-4.1\",\n    Streaming: true,\n})\n\nsession.On(func(event copilot.SessionEvent) {\n    if event.Type == \"assistant.message_delta\" {\n        fmt.Print(*event.Data.DeltaContent)\n    }\n    if event.Type == \"session.idle\" {\n        fmt.Println()\n    }\n})\n\n_, err = session.SendAndWait(copilot.MessageOptions{Prompt: \"Tell me a short joke\"}, 0)\n```\n\n### .NET\n```csharp\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n    Streaming = true,\n});\n\nsession.On(ev =>\n{\n    if (ev is AssistantMessageDeltaEvent deltaEvent)\n        Console.Write(deltaEvent.Data.DeltaContent);\n    if (ev is SessionIdleEvent)\n        Console.WriteLine();\n});\n\nawait session.SendAndWaitAsync(new MessageOptions { Prompt = \"Tell me a short joke\" });\n```\n\n## Custom Tools\n\nDefine tools that Copilot can invoke during reasoning. When you define a tool, you tell Copilot:\n1. **What the tool does** (description)\n2. **What parameters it needs** (schema)\n3. **What code to run** (handler)\n\n### TypeScript (JSON Schema)\n```typescript\nimport { CopilotClient, approveAll, defineTool, SessionEvent } from \"@github\u002Fcopilot-sdk\";\n\nconst getWeather = defineTool(\"get_weather\", {\n    description: \"Get the current weather for a city\",\n    parameters: {\n        type: \"object\",\n        properties: {\n            city: { type: \"string\", description: \"The city name\" },\n        },\n        required: [\"city\"],\n    },\n    handler: async (args: { city: string }) => {\n        const { city } = args;\n        \u002F\u002F In a real app, call a weather API here\n        const conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"];\n        const temp = Math.floor(Math.random() * 30) + 50;\n        const condition = conditions[Math.floor(Math.random() * conditions.length)];\n        return { city, temperature: `${temp}°F`, condition };\n    },\n});\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    streaming: true,\n    tools: [getWeather],\n});\n\nsession.on((event: SessionEvent) => {\n    if (event.type === \"assistant.message_delta\") {\n        process.stdout.write(event.data.deltaContent);\n    }\n});\n\nawait session.sendAndWait({\n    prompt: \"What's the weather like in Seattle and Tokyo?\",\n});\n\nawait client.stop();\nprocess.exit(0);\n```\n\n### Python (Pydantic)\n```python\nimport asyncio\nimport random\nimport sys\nfrom copilot import CopilotClient, PermissionHandler\nfrom copilot.tools import define_tool\nfrom copilot.generated.session_events import SessionEventType\nfrom pydantic import BaseModel, Field\n\nclass GetWeatherParams(BaseModel):\n    city: str = Field(description=\"The name of the city to get weather for\")\n\n@define_tool(description=\"Get the current weather for a city\")\nasync def get_weather(params: GetWeatherParams) -> dict:\n    city = params.city\n    conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"]\n    temp = random.randint(50, 80)\n    condition = random.choice(conditions)\n    return {\"city\": city, \"temperature\": f\"{temp}°F\", \"condition\": condition}\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n            streaming=True,\n            tools=[get_weather],\n        ) as session:\n            def handle_event(event):\n                if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:\n                    sys.stdout.write(event.data.delta_content)\n                    sys.stdout.flush()\n\n            session.on(handle_event)\n            await session.send_and_wait(\n                \"What's the weather like in Seattle and Tokyo?\"\n            )\n\nasyncio.run(main())\n```\n\n### Go\n```go\ntype WeatherParams struct {\n    City string `json:\"city\" jsonschema:\"The city name\"`\n}\n\ntype WeatherResult struct {\n    City        string `json:\"city\"`\n    Temperature string `json:\"temperature\"`\n    Condition   string `json:\"condition\"`\n}\n\ngetWeather := copilot.DefineTool(\n    \"get_weather\",\n    \"Get the current weather for a city\",\n    func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {\n        conditions := []string{\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"}\n        temp := rand.Intn(30) + 50\n        condition := conditions[rand.Intn(len(conditions))]\n        return WeatherResult{\n            City:        params.City,\n            Temperature: fmt.Sprintf(\"%d°F\", temp),\n            Condition:   condition,\n        }, nil\n    },\n)\n\nsession, _ := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n    Model:     \"gpt-4.1\",\n    Streaming: true,\n    Tools:     []copilot.Tool{getWeather},\n})\n```\n\n### .NET (Microsoft.Extensions.AI)\n```csharp\nusing GitHub.Copilot.SDK;\nusing Microsoft.Extensions.AI;\nusing System.ComponentModel;\n\nvar getWeather = AIFunctionFactory.Create(\n    ([Description(\"The city name\")] string city) =>\n    {\n        var conditions = new[] { \"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\" };\n        var temp = Random.Shared.Next(50, 80);\n        var condition = conditions[Random.Shared.Next(conditions.Length)];\n        return new { city, temperature = $\"{temp}°F\", condition };\n    },\n    \"get_weather\",\n    \"Get the current weather for a city\"\n);\n\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n    Streaming = true,\n    Tools = [getWeather],\n});\n```\n\n## How Tools Work\n\nWhen Copilot decides to call your tool:\n1. Copilot sends a tool call request with the parameters\n2. The SDK runs your handler function\n3. The result is sent back to Copilot\n4. Copilot incorporates the result into its response\n\nCopilot decides when to call your tool based on the user's question and your tool's description.\n\n## Interactive CLI Assistant\n\nBuild a complete interactive assistant:\n\n### TypeScript\n```typescript\nimport { CopilotClient, approveAll, defineTool, SessionEvent } from \"@github\u002Fcopilot-sdk\";\nimport * as readline from \"readline\";\n\nconst getWeather = defineTool(\"get_weather\", {\n    description: \"Get the current weather for a city\",\n    parameters: {\n        type: \"object\",\n        properties: {\n            city: { type: \"string\", description: \"The city name\" },\n        },\n        required: [\"city\"],\n    },\n    handler: async ({ city }) => {\n        const conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"];\n        const temp = Math.floor(Math.random() * 30) + 50;\n        const condition = conditions[Math.floor(Math.random() * conditions.length)];\n        return { city, temperature: `${temp}°F`, condition };\n    },\n});\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    streaming: true,\n    tools: [getWeather],\n});\n\nsession.on((event: SessionEvent) => {\n    if (event.type === \"assistant.message_delta\") {\n        process.stdout.write(event.data.deltaContent);\n    }\n});\n\nconst rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout,\n});\n\nconsole.log(\"Weather Assistant (type 'exit' to quit)\");\nconsole.log(\"Try: 'What's the weather in Paris?'\\n\");\n\nconst prompt = () => {\n    rl.question(\"You: \", async (input) => {\n        if (input.toLowerCase() === \"exit\") {\n            await client.stop();\n            rl.close();\n            return;\n        }\n\n        process.stdout.write(\"Assistant: \");\n        await session.sendAndWait({ prompt: input });\n        console.log(\"\\n\");\n        prompt();\n    });\n};\n\nprompt();\n```\n\n### Python\n```python\nimport asyncio\nimport random\nimport sys\nfrom copilot import CopilotClient, PermissionHandler\nfrom copilot.tools import define_tool\nfrom copilot.generated.session_events import SessionEventType\nfrom pydantic import BaseModel, Field\n\nclass GetWeatherParams(BaseModel):\n    city: str = Field(description=\"The name of the city to get weather for\")\n\n@define_tool(description=\"Get the current weather for a city\")\nasync def get_weather(params: GetWeatherParams) -> dict:\n    conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"]\n    temp = random.randint(50, 80)\n    condition = random.choice(conditions)\n    return {\"city\": params.city, \"temperature\": f\"{temp}°F\", \"condition\": condition}\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n            streaming=True,\n            tools=[get_weather],\n        ) as session:\n            def handle_event(event):\n                if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:\n                    sys.stdout.write(event.data.delta_content)\n                    sys.stdout.flush()\n\n            session.on(handle_event)\n\n            print(\"Weather Assistant (type 'exit' to quit)\")\n            print(\"Try: 'What's the weather in Paris?'\\n\")\n\n            while True:\n                try:\n                    user_input = input(\"You: \")\n                except EOFError:\n                    break\n\n                if user_input.lower() == \"exit\":\n                    break\n\n                sys.stdout.write(\"Assistant: \")\n                await session.send_and_wait(user_input)\n                print(\"\\n\")\n\nasyncio.run(main())\n```\n\n## MCP Server Integration\n\nConnect to MCP (Model Context Protocol) servers for pre-built tools. Connect to GitHub's MCP server for repository, issue, and PR access:\n\n### TypeScript\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    mcpServers: {\n        github: {\n            type: \"http\",\n            url: \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n});\n```\n\n### Python\n```python\nasync with await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    model=\"gpt-4.1\",\n    mcp_servers={\n        \"github\": {\n            \"type\": \"http\",\n            \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n) as session:\n    ...\n```\n\n### Go\n```go\nsession, _ := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n    Model: \"gpt-4.1\",\n    MCPServers: map[string]copilot.MCPServerConfig{\n        \"github\": {\n            \"type\": \"http\",\n            \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n})\n```\n\n### .NET\n```csharp\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n    McpServers = new Dictionary\u003Cstring, McpServerConfig>\n    {\n        [\"github\"] = new McpServerConfig\n        {\n            Type = \"http\",\n            Url = \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n});\n```\n\n## Custom Agents\n\nDefine specialized AI personas for specific tasks:\n\n### TypeScript\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    customAgents: [{\n        name: \"pr-reviewer\",\n        displayName: \"PR Reviewer\",\n        description: \"Reviews pull requests for best practices\",\n        prompt: \"You are an expert code reviewer. Focus on security, performance, and maintainability.\",\n    }],\n});\n```\n\n### Python\n```python\nasync with await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    model=\"gpt-4.1\",\n    custom_agents=[{\n        \"name\": \"pr-reviewer\",\n        \"display_name\": \"PR Reviewer\",\n        \"description\": \"Reviews pull requests for best practices\",\n        \"prompt\": \"You are an expert code reviewer. Focus on security, performance, and maintainability.\",\n    }],\n) as session:\n    ...\n```\n\n## System Message\n\nCustomize the AI's behavior and personality:\n\n### TypeScript\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    systemMessage: {\n        content: \"You are a helpful assistant for our engineering team. Always be concise.\",\n    },\n});\n```\n\n### Python\n```python\nasync with await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    model=\"gpt-4.1\",\n    system_message={\n        \"content\": \"You are a helpful assistant for our engineering team. Always be concise.\",\n    },\n) as session:\n    ...\n```\n\n## External CLI Server\n\nRun the CLI in server mode separately and connect the SDK to it. Useful for debugging, resource sharing, or custom environments.\n\n### Start CLI in Server Mode\n```bash\ncopilot --server --port 4321\n```\n\n### Connect SDK to External Server\n\n#### TypeScript\n```typescript\nconst client = new CopilotClient({\n    cliUrl: \"localhost:4321\"\n});\n\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n});\n```\n\n#### Python\n```python\nfrom copilot import CopilotClient, PermissionHandler, RuntimeConnection\n\nasync with CopilotClient(\n    connection=RuntimeConnection.for_uri(\"localhost:4321\")\n) as client:\n    async with await client.create_session(\n        on_permission_request=PermissionHandler.approve_all,\n        model=\"gpt-4.1\",\n    ) as session:\n        ...\n```\n\n#### Go\n```go\nclient := copilot.NewClient(&copilot.ClientOptions{\n    CLIUrl: \"localhost:4321\",\n})\n\nif err := client.Start(); err != nil {\n    log.Fatal(err)\n}\n\nsession, _ := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n\tModel:               \"gpt-4.1\",\n})\n```\n\n#### .NET\n```csharp\nusing var client = new CopilotClient(new CopilotClientOptions\n{\n    CliUrl = \"localhost:4321\"\n});\n\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n});\n```\n\n**Note:** When configured to use an external server, the SDK manages only its connection and does not manage the external process.\n\n## Event Types\n\n| Event | Description |\n|-------|-------------|\n| `user.message` | User input added |\n| `assistant.message` | Complete model response |\n| `assistant.message_delta` | Streaming response chunk |\n| `assistant.reasoning` | Model reasoning (model-dependent) |\n| `assistant.reasoning_delta` | Streaming reasoning chunk |\n| `tool.execution_start` | Tool invocation started |\n| `tool.execution_complete` | Tool execution finished |\n| `session.idle` | No active processing |\n| `session.error` | Error occurred |\n\n## Client Configuration\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `cliPath` | Path to Copilot CLI executable | System PATH |\n| `cliUrl` | Connect to existing server (e.g., \"localhost:4321\") | None |\n| `port` | Server communication port | Random |\n| `useStdio` | Use stdio transport instead of TCP | true |\n| `logLevel` | Logging verbosity | \"info\" |\n| `autoStart` | Launch server automatically | true |\n| `autoRestart` | Restart on crashes | true |\n| `cwd` | Working directory for CLI process | Inherited |\n\n## Session Configuration\n\n| Option | Description |\n|--------|-------------|\n| `model` | LLM to use (\"gpt-4.1\", \"claude-sonnet-4.5\", etc.) |\n| `sessionId` | Custom session identifier |\n| `tools` | Custom tool definitions |\n| `mcpServers` | MCP server connections |\n| `customAgents` | Custom agent personas |\n| `systemMessage` | Override default system prompt |\n| `streaming` | Enable incremental response chunks |\n| `availableTools` | Whitelist of permitted tools |\n| `excludedTools` | Blacklist of disabled tools |\n\n## Session Persistence\n\nSave and resume conversations across restarts:\n\n### Create with Custom ID\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    sessionId: \"user-123-conversation\",\n    model: \"gpt-4.1\"\n});\n```\n\n### Resume Session\n```typescript\nconst session = await client.resumeSession(\"user-123-conversation\", { onPermissionRequest: approveAll });\nawait session.send({ prompt: \"What did we discuss earlier?\" });\n```\n\n### List and Delete Sessions\n```typescript\nconst sessions = await client.listSessions();\nawait client.deleteSession(\"old-session-id\");\n```\n\n## Error Handling\n\n```typescript\ntry {\n    const client = new CopilotClient();\n    const session = await client.createSession({\n        onPermissionRequest: approveAll,\n        model: \"gpt-4.1\",\n    });\n    const response = await session.sendAndWait(\n        { prompt: \"Hello!\" },\n        30000 \u002F\u002F timeout in ms\n    );\n} catch (error) {\n    if (error.code === \"ENOENT\") {\n        console.error(\"Copilot CLI not installed\");\n    } else if (error.code === \"ECONNREFUSED\") {\n        console.error(\"Cannot connect to Copilot server\");\n    } else {\n        console.error(\"Error:\", error.message);\n    }\n} finally {\n    await client.stop();\n}\n```\n\n## Graceful Shutdown\n\n```typescript\nprocess.on(\"SIGINT\", async () => {\n    console.log(\"Shutting down...\");\n    await client.stop();\n    process.exit(0);\n});\n```\n\n## Common Patterns\n\n### Multi-turn Conversation\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n});\n\nawait session.sendAndWait({ prompt: \"My name is Alice\" });\nawait session.sendAndWait({ prompt: \"What's my name?\" });\n\u002F\u002F Response: \"Your name is Alice\"\n```\n\n### File Attachments\n```typescript\nawait session.send({\n    prompt: \"Analyze this file\",\n    attachments: [{\n        type: \"file\",\n        path: \".\u002Fdata.csv\",\n        displayName: \"Sales Data\"\n    }]\n});\n```\n\n### Abort Long Operations\n```typescript\nconst timeoutId = setTimeout(() => {\n    session.abort();\n}, 60000);\n\nsession.on((event) => {\n    if (event.type === \"session.idle\") {\n        clearTimeout(timeoutId);\n    }\n});\n```\n\n## Available Models\n\nQuery available models at runtime:\n\n```typescript\nconst models = await client.getModels();\n\u002F\u002F Returns: [\"gpt-4.1\", \"gpt-4o\", \"claude-sonnet-4.5\", ...]\n```\n\n## Best Practices\n\n1. **Always clean up**: Use language-native context managers or disposal, or explicitly disconnect sessions and stop clients\n2. **Set timeouts**: Use `sendAndWait` with timeout for long operations\n3. **Handle events**: Subscribe to error events for robust error handling\n4. **Use streaming**: Enable streaming for better UX on long responses\n5. **Persist sessions**: Use custom session IDs for multi-turn conversations\n6. **Define clear tools**: Write descriptive tool names and descriptions\n\n## Architecture\n\n```\nYour Application\n       |\n  SDK Client\n       | JSON-RPC\n  Copilot CLI (server mode)\n       |\n  GitHub (models, auth)\n```\n\nThe SDK manages the CLI process lifecycle automatically. All communication happens via JSON-RPC over stdio or TCP.\n\n## Resources\n\n- **GitHub Repository**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\n- **Getting Started Tutorial**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\u002Fblob\u002Fmain\u002Fdocs\u002Ftutorials\u002Ffirst-app.md\n- **GitHub MCP Server**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fgithub-mcp-server\n- **MCP Servers Directory**: https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers\n- **Cookbook**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\u002Ftree\u002Fmain\u002Fcookbook\n- **Samples**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\u002Ftree\u002Fmain\u002Fsamples\n\n## Status\n\nThis SDK is in **Technical Preview** and may have breaking changes. Not recommended for production use yet.\n","# Microsoft Copilot SDK\n\nEmbed Copilot's agentic workflows in any application using Python, TypeScript, Go, or .NET.\n\n## Overview\n\nThe Microsoft Copilot SDK is transitioning from the GitHub Copilot SDK. It is becoming the programmable interface for the Microsoft Copilot harness, the shared agent foundation used across Microsoft and GitHub products. This transition is happening in phases, and no immediate changes are required for existing users. Package names, namespaces, and some documentation may continue to use GitHub branding during the transition.\n\nThis guide keeps the currently published package names and imports in its examples. Follow the [official transition announcement](https:\u002F\u002Fgithub.blog\u002Fchangelog\u002F2026-10-28-github-copilot-sdk-is-becoming-microsoft-copilot-sdk\u002F) for migration updates.\n\nThe SDK provides a production-tested agent runtime you can invoke programmatically. You define agent behavior, while Copilot handles planning, tool invocation, file edits, and more.\n\n## Prerequisites\n\n1. **GitHub Copilot access** and an authenticated environment\n2. **Language runtime**: Node.js ^20.19.0 or >=22.12.0, Python 3.11+, Go 1.24+, or a .NET Standard 2.0-compatible implementation\n3. **Go**: GitHub Copilot CLI installed and authenticated ([Installation guide](https:\u002F\u002Fdocs.github.com\u002Fen\u002Fcopilot\u002Fhow-tos\u002Fset-up\u002Finstall-copilot-cli))\n\nThe TypeScript, Python, and .NET packages use a bundled Copilot runtime by default, so they do not need a separate CLI installation.\n\n## Installation\n\n### Node.js\u002FTypeScript\n```bash\nmkdir copilot-demo && cd copilot-demo\nnpm init -y --init-type module\nnpm install @github\u002Fcopilot-sdk tsx\n```\n\n### Python\n```bash\npip install github-copilot-sdk\n\n# Optional: pre-download the bundled runtime instead of downloading it on first use\npython -m copilot download-runtime\n```\n\nPublished Python wheels include a pinned runtime version. The pre-download command caches that runtime locally; if skipped, the SDK attempts to download it automatically on first use.\n\n### Go\n```bash\nmkdir copilot-demo && cd copilot-demo\ngo mod init copilot-demo\ngo get github.com\u002Fgithub\u002Fcopilot-sdk\u002Fgo\n```\n\n### .NET\n```bash\ndotnet new console -n CopilotDemo && cd CopilotDemo\ndotnet add package GitHub.Copilot.SDK\n```\n\n## Quick Start\n\n### TypeScript\n```typescript\nimport { CopilotClient, approveAll } from \"@github\u002Fcopilot-sdk\";\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n});\n\nconst response = await session.sendAndWait({ prompt: \"What is 2 + 2?\" });\nconsole.log(response?.data.content);\n\nawait client.stop();\nprocess.exit(0);\n```\n\nRun: `npx tsx index.ts`\n\n### Python\n```python\nimport asyncio\nfrom copilot import CopilotClient, PermissionHandler\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n        ) as session:\n            response = await session.send_and_wait(\"What is 2 + 2?\")\n            print(response.data.content)\n\nasyncio.run(main())\n```\n\n### Go\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"os\"\n    copilot \"github.com\u002Fgithub\u002Fcopilot-sdk\u002Fgo\"\n)\n\nfunc main() {\n    client := copilot.NewClient(nil)\n    if err := client.Start(); err != nil {\n        log.Fatal(err)\n    }\n    defer client.Stop()\n\n    session, err := client.CreateSession(&copilot.SessionConfig{\n        OnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n        Model:               \"gpt-4.1\",\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    response, err := session.SendAndWait(copilot.MessageOptions{Prompt: \"What is 2 + 2?\"}, 0)\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Println(*response.Data.Content)\n    os.Exit(0)\n}\n```\n\n### .NET (C#)\n```csharp\nusing GitHub.Copilot.SDK;\n\nawait using var client = new CopilotClient();\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n});\n\nvar response = await session.SendAndWaitAsync(new MessageOptions { Prompt = \"What is 2 + 2?\" });\nConsole.WriteLine(response?.Data.Content);\n```\n\nRun: `dotnet run`\n\n## Streaming Responses\n\nEnable real-time output for better UX:\n\n### TypeScript\n```typescript\nimport { CopilotClient, approveAll, SessionEvent } from \"@github\u002Fcopilot-sdk\";\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    streaming: true,\n});\n\nsession.on((event: SessionEvent) => {\n    if (event.type === \"assistant.message_delta\") {\n        process.stdout.write(event.data.deltaContent);\n    }\n    if (event.type === \"session.idle\") {\n        console.log(); \u002F\u002F New line when done\n    }\n});\n\nawait session.sendAndWait({ prompt: \"Tell me a short joke\" });\n\nawait client.stop();\nprocess.exit(0);\n```\n\n### Python\n```python\nimport asyncio\nimport sys\nfrom copilot import CopilotClient, PermissionHandler\nfrom copilot.generated.session_events import SessionEventType\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n            streaming=True,\n        ) as session:\n            def handle_event(event):\n                if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:\n                    sys.stdout.write(event.data.delta_content)\n                    sys.stdout.flush()\n                if event.type == SessionEventType.SESSION_IDLE:\n                    print()\n\n            session.on(handle_event)\n            await session.send_and_wait(\"Tell me a short joke\")\n\nasyncio.run(main())\n```\n\n### Go\n```go\nsession, err := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n    Model:     \"gpt-4.1\",\n    Streaming: true,\n})\n\nsession.On(func(event copilot.SessionEvent) {\n    if event.Type == \"assistant.message_delta\" {\n        fmt.Print(*event.Data.DeltaContent)\n    }\n    if event.Type == \"session.idle\" {\n        fmt.Println()\n    }\n})\n\n_, err = session.SendAndWait(copilot.MessageOptions{Prompt: \"Tell me a short joke\"}, 0)\n```\n\n### .NET\n```csharp\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n    Streaming = true,\n});\n\nsession.On(ev =>\n{\n    if (ev is AssistantMessageDeltaEvent deltaEvent)\n        Console.Write(deltaEvent.Data.DeltaContent);\n    if (ev is SessionIdleEvent)\n        Console.WriteLine();\n});\n\nawait session.SendAndWaitAsync(new MessageOptions { Prompt = \"Tell me a short joke\" });\n```\n\n## Custom Tools\n\nDefine tools that Copilot can invoke during reasoning. When you define a tool, you tell Copilot:\n1. **What the tool does** (description)\n2. **What parameters it needs** (schema)\n3. **What code to run** (handler)\n\n### TypeScript (JSON Schema)\n```typescript\nimport { CopilotClient, approveAll, defineTool, SessionEvent } from \"@github\u002Fcopilot-sdk\";\n\nconst getWeather = defineTool(\"get_weather\", {\n    description: \"Get the current weather for a city\",\n    parameters: {\n        type: \"object\",\n        properties: {\n            city: { type: \"string\", description: \"The city name\" },\n        },\n        required: [\"city\"],\n    },\n    handler: async (args: { city: string }) => {\n        const { city } = args;\n        \u002F\u002F In a real app, call a weather API here\n        const conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"];\n        const temp = Math.floor(Math.random() * 30) + 50;\n        const condition = conditions[Math.floor(Math.random() * conditions.length)];\n        return { city, temperature: `${temp}°F`, condition };\n    },\n});\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    streaming: true,\n    tools: [getWeather],\n});\n\nsession.on((event: SessionEvent) => {\n    if (event.type === \"assistant.message_delta\") {\n        process.stdout.write(event.data.deltaContent);\n    }\n});\n\nawait session.sendAndWait({\n    prompt: \"What's the weather like in Seattle and Tokyo?\",\n});\n\nawait client.stop();\nprocess.exit(0);\n```\n\n### Python (Pydantic)\n```python\nimport asyncio\nimport random\nimport sys\nfrom copilot import CopilotClient, PermissionHandler\nfrom copilot.tools import define_tool\nfrom copilot.generated.session_events import SessionEventType\nfrom pydantic import BaseModel, Field\n\nclass GetWeatherParams(BaseModel):\n    city: str = Field(description=\"The name of the city to get weather for\")\n\n@define_tool(description=\"Get the current weather for a city\")\nasync def get_weather(params: GetWeatherParams) -> dict:\n    city = params.city\n    conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"]\n    temp = random.randint(50, 80)\n    condition = random.choice(conditions)\n    return {\"city\": city, \"temperature\": f\"{temp}°F\", \"condition\": condition}\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n            streaming=True,\n            tools=[get_weather],\n        ) as session:\n            def handle_event(event):\n                if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:\n                    sys.stdout.write(event.data.delta_content)\n                    sys.stdout.flush()\n\n            session.on(handle_event)\n            await session.send_and_wait(\n                \"What's the weather like in Seattle and Tokyo?\"\n            )\n\nasyncio.run(main())\n```\n\n### Go\n```go\ntype WeatherParams struct {\n    City string `json:\"city\" jsonschema:\"The city name\"`\n}\n\ntype WeatherResult struct {\n    City        string `json:\"city\"`\n    Temperature string `json:\"temperature\"`\n    Condition   string `json:\"condition\"`\n}\n\ngetWeather := copilot.DefineTool(\n    \"get_weather\",\n    \"Get the current weather for a city\",\n    func(params WeatherParams, inv copilot.ToolInvocation) (WeatherResult, error) {\n        conditions := []string{\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"}\n        temp := rand.Intn(30) + 50\n        condition := conditions[rand.Intn(len(conditions))]\n        return WeatherResult{\n            City:        params.City,\n            Temperature: fmt.Sprintf(\"%d°F\", temp),\n            Condition:   condition,\n        }, nil\n    },\n)\n\nsession, _ := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n    Model:     \"gpt-4.1\",\n    Streaming: true,\n    Tools:     []copilot.Tool{getWeather},\n})\n```\n\n### .NET (Microsoft.Extensions.AI)\n```csharp\nusing GitHub.Copilot.SDK;\nusing Microsoft.Extensions.AI;\nusing System.ComponentModel;\n\nvar getWeather = AIFunctionFactory.Create(\n    ([Description(\"The city name\")] string city) =>\n    {\n        var conditions = new[] { \"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\" };\n        var temp = Random.Shared.Next(50, 80);\n        var condition = conditions[Random.Shared.Next(conditions.Length)];\n        return new { city, temperature = $\"{temp}°F\", condition };\n    },\n    \"get_weather\",\n    \"Get the current weather for a city\"\n);\n\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n    Streaming = true,\n    Tools = [getWeather],\n});\n```\n\n## How Tools Work\n\nWhen Copilot decides to call your tool:\n1. Copilot sends a tool call request with the parameters\n2. The SDK runs your handler function\n3. The result is sent back to Copilot\n4. Copilot incorporates the result into its response\n\nCopilot decides when to call your tool based on the user's question and your tool's description.\n\n## Interactive CLI Assistant\n\nBuild a complete interactive assistant:\n\n### TypeScript\n```typescript\nimport { CopilotClient, approveAll, defineTool, SessionEvent } from \"@github\u002Fcopilot-sdk\";\nimport * as readline from \"readline\";\n\nconst getWeather = defineTool(\"get_weather\", {\n    description: \"Get the current weather for a city\",\n    parameters: {\n        type: \"object\",\n        properties: {\n            city: { type: \"string\", description: \"The city name\" },\n        },\n        required: [\"city\"],\n    },\n    handler: async ({ city }) => {\n        const conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"];\n        const temp = Math.floor(Math.random() * 30) + 50;\n        const condition = conditions[Math.floor(Math.random() * conditions.length)];\n        return { city, temperature: `${temp}°F`, condition };\n    },\n});\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    streaming: true,\n    tools: [getWeather],\n});\n\nsession.on((event: SessionEvent) => {\n    if (event.type === \"assistant.message_delta\") {\n        process.stdout.write(event.data.deltaContent);\n    }\n});\n\nconst rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout,\n});\n\nconsole.log(\"Weather Assistant (type 'exit' to quit)\");\nconsole.log(\"Try: 'What's the weather in Paris?'\\n\");\n\nconst prompt = () => {\n    rl.question(\"You: \", async (input) => {\n        if (input.toLowerCase() === \"exit\") {\n            await client.stop();\n            rl.close();\n            return;\n        }\n\n        process.stdout.write(\"Assistant: \");\n        await session.sendAndWait({ prompt: input });\n        console.log(\"\\n\");\n        prompt();\n    });\n};\n\nprompt();\n```\n\n### Python\n```python\nimport asyncio\nimport random\nimport sys\nfrom copilot import CopilotClient, PermissionHandler\nfrom copilot.tools import define_tool\nfrom copilot.generated.session_events import SessionEventType\nfrom pydantic import BaseModel, Field\n\nclass GetWeatherParams(BaseModel):\n    city: str = Field(description=\"The name of the city to get weather for\")\n\n@define_tool(description=\"Get the current weather for a city\")\nasync def get_weather(params: GetWeatherParams) -> dict:\n    conditions = [\"sunny\", \"cloudy\", \"rainy\", \"partly cloudy\"]\n    temp = random.randint(50, 80)\n    condition = random.choice(conditions)\n    return {\"city\": params.city, \"temperature\": f\"{temp}°F\", \"condition\": condition}\n\nasync def main():\n    async with CopilotClient() as client:\n        async with await client.create_session(\n            on_permission_request=PermissionHandler.approve_all,\n            model=\"gpt-4.1\",\n            streaming=True,\n            tools=[get_weather],\n        ) as session:\n            def handle_event(event):\n                if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:\n                    sys.stdout.write(event.data.delta_content)\n                    sys.stdout.flush()\n\n            session.on(handle_event)\n\n            print(\"Weather Assistant (type 'exit' to quit)\")\n            print(\"Try: 'What's the weather in Paris?'\\n\")\n\n            while True:\n                try:\n                    user_input = input(\"You: \")\n                except EOFError:\n                    break\n\n                if user_input.lower() == \"exit\":\n                    break\n\n                sys.stdout.write(\"Assistant: \")\n                await session.send_and_wait(user_input)\n                print(\"\\n\")\n\nasyncio.run(main())\n```\n\n## MCP Server Integration\n\nConnect to MCP (Model Context Protocol) servers for pre-built tools. Connect to GitHub's MCP server for repository, issue, and PR access:\n\n### TypeScript\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    mcpServers: {\n        github: {\n            type: \"http\",\n            url: \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n});\n```\n\n### Python\n```python\nasync with await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    model=\"gpt-4.1\",\n    mcp_servers={\n        \"github\": {\n            \"type\": \"http\",\n            \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n) as session:\n    ...\n```\n\n### Go\n```go\nsession, _ := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n    Model: \"gpt-4.1\",\n    MCPServers: map[string]copilot.MCPServerConfig{\n        \"github\": {\n            \"type\": \"http\",\n            \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n})\n```\n\n### .NET\n```csharp\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n    McpServers = new Dictionary\u003Cstring, McpServerConfig>\n    {\n        [\"github\"] = new McpServerConfig\n        {\n            Type = \"http\",\n            Url = \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n        },\n    },\n});\n```\n\n## Custom Agents\n\nDefine specialized AI personas for specific tasks:\n\n### TypeScript\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    customAgents: [{\n        name: \"pr-reviewer\",\n        displayName: \"PR Reviewer\",\n        description: \"Reviews pull requests for best practices\",\n        prompt: \"You are an expert code reviewer. Focus on security, performance, and maintainability.\",\n    }],\n});\n```\n\n### Python\n```python\nasync with await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    model=\"gpt-4.1\",\n    custom_agents=[{\n        \"name\": \"pr-reviewer\",\n        \"display_name\": \"PR Reviewer\",\n        \"description\": \"Reviews pull requests for best practices\",\n        \"prompt\": \"You are an expert code reviewer. Focus on security, performance, and maintainability.\",\n    }],\n) as session:\n    ...\n```\n\n## System Message\n\nCustomize the AI's behavior and personality:\n\n### TypeScript\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n    systemMessage: {\n        content: \"You are a helpful assistant for our engineering team. Always be concise.\",\n    },\n});\n```\n\n### Python\n```python\nasync with await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    model=\"gpt-4.1\",\n    system_message={\n        \"content\": \"You are a helpful assistant for our engineering team. Always be concise.\",\n    },\n) as session:\n    ...\n```\n\n## External CLI Server\n\nRun the CLI in server mode separately and connect the SDK to it. Useful for debugging, resource sharing, or custom environments.\n\n### Start CLI in Server Mode\n```bash\ncopilot --server --port 4321\n```\n\n### Connect SDK to External Server\n\n#### TypeScript\n```typescript\nconst client = new CopilotClient({\n    cliUrl: \"localhost:4321\"\n});\n\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n});\n```\n\n#### Python\n```python\nfrom copilot import CopilotClient, PermissionHandler, RuntimeConnection\n\nasync with CopilotClient(\n    connection=RuntimeConnection.for_uri(\"localhost:4321\")\n) as client:\n    async with await client.create_session(\n        on_permission_request=PermissionHandler.approve_all,\n        model=\"gpt-4.1\",\n    ) as session:\n        ...\n```\n\n#### Go\n```go\nclient := copilot.NewClient(&copilot.ClientOptions{\n    CLIUrl: \"localhost:4321\",\n})\n\nif err := client.Start(); err != nil {\n    log.Fatal(err)\n}\n\nsession, _ := client.CreateSession(&copilot.SessionConfig{\n\tOnPermissionRequest: copilot.PermissionHandler.ApproveAll,\n\tModel:               \"gpt-4.1\",\n})\n```\n\n#### .NET\n```csharp\nusing var client = new CopilotClient(new CopilotClientOptions\n{\n    CliUrl = \"localhost:4321\"\n});\n\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    OnPermissionRequest = PermissionHandler.ApproveAll,\n    Model = \"gpt-4.1\",\n});\n```\n\n**Note:** When configured to use an external server, the SDK manages only its connection and does not manage the external process.\n\n## Event Types\n\n| Event | Description |\n|-------|-------------|\n| `user.message` | User input added |\n| `assistant.message` | Complete model response |\n| `assistant.message_delta` | Streaming response chunk |\n| `assistant.reasoning` | Model reasoning (model-dependent) |\n| `assistant.reasoning_delta` | Streaming reasoning chunk |\n| `tool.execution_start` | Tool invocation started |\n| `tool.execution_complete` | Tool execution finished |\n| `session.idle` | No active processing |\n| `session.error` | Error occurred |\n\n## Client Configuration\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `cliPath` | Path to Copilot CLI executable | System PATH |\n| `cliUrl` | Connect to existing server (e.g., \"localhost:4321\") | None |\n| `port` | Server communication port | Random |\n| `useStdio` | Use stdio transport instead of TCP | true |\n| `logLevel` | Logging verbosity | \"info\" |\n| `autoStart` | Launch server automatically | true |\n| `autoRestart` | Restart on crashes | true |\n| `cwd` | Working directory for CLI process | Inherited |\n\n## Session Configuration\n\n| Option | Description |\n|--------|-------------|\n| `model` | LLM to use (\"gpt-4.1\", \"claude-sonnet-4.5\", etc.) |\n| `sessionId` | Custom session identifier |\n| `tools` | Custom tool definitions |\n| `mcpServers` | MCP server connections |\n| `customAgents` | Custom agent personas |\n| `systemMessage` | Override default system prompt |\n| `streaming` | Enable incremental response chunks |\n| `availableTools` | Whitelist of permitted tools |\n| `excludedTools` | Blacklist of disabled tools |\n\n## Session Persistence\n\nSave and resume conversations across restarts:\n\n### Create with Custom ID\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    sessionId: \"user-123-conversation\",\n    model: \"gpt-4.1\"\n});\n```\n\n### Resume Session\n```typescript\nconst session = await client.resumeSession(\"user-123-conversation\", { onPermissionRequest: approveAll });\nawait session.send({ prompt: \"What did we discuss earlier?\" });\n```\n\n### List and Delete Sessions\n```typescript\nconst sessions = await client.listSessions();\nawait client.deleteSession(\"old-session-id\");\n```\n\n## Error Handling\n\n```typescript\ntry {\n    const client = new CopilotClient();\n    const session = await client.createSession({\n        onPermissionRequest: approveAll,\n        model: \"gpt-4.1\",\n    });\n    const response = await session.sendAndWait(\n        { prompt: \"Hello!\" },\n        30000 \u002F\u002F timeout in ms\n    );\n} catch (error) {\n    if (error.code === \"ENOENT\") {\n        console.error(\"Copilot CLI not installed\");\n    } else if (error.code === \"ECONNREFUSED\") {\n        console.error(\"Cannot connect to Copilot server\");\n    } else {\n        console.error(\"Error:\", error.message);\n    }\n} finally {\n    await client.stop();\n}\n```\n\n## Graceful Shutdown\n\n```typescript\nprocess.on(\"SIGINT\", async () => {\n    console.log(\"Shutting down...\");\n    await client.stop();\n    process.exit(0);\n});\n```\n\n## Common Patterns\n\n### Multi-turn Conversation\n```typescript\nconst session = await client.createSession({\n    onPermissionRequest: approveAll,\n    model: \"gpt-4.1\",\n});\n\nawait session.sendAndWait({ prompt: \"My name is Alice\" });\nawait session.sendAndWait({ prompt: \"What's my name?\" });\n\u002F\u002F Response: \"Your name is Alice\"\n```\n\n### File Attachments\n```typescript\nawait session.send({\n    prompt: \"Analyze this file\",\n    attachments: [{\n        type: \"file\",\n        path: \".\u002Fdata.csv\",\n        displayName: \"Sales Data\"\n    }]\n});\n```\n\n### Abort Long Operations\n```typescript\nconst timeoutId = setTimeout(() => {\n    session.abort();\n}, 60000);\n\nsession.on((event) => {\n    if (event.type === \"session.idle\") {\n        clearTimeout(timeoutId);\n    }\n});\n```\n\n## Available Models\n\nQuery available models at runtime:\n\n```typescript\nconst models = await client.getModels();\n\u002F\u002F Returns: [\"gpt-4.1\", \"gpt-4o\", \"claude-sonnet-4.5\", ...]\n```\n\n## Best Practices\n\n1. **Always clean up**: Use language-native context managers or disposal, or explicitly disconnect sessions and stop clients\n2. **Set timeouts**: Use `sendAndWait` with timeout for long operations\n3. **Handle events**: Subscribe to error events for robust error handling\n4. **Use streaming**: Enable streaming for better UX on long responses\n5. **Persist sessions**: Use custom session IDs for multi-turn conversations\n6. **Define clear tools**: Write descriptive tool names and descriptions\n\n## Architecture\n\n```\nYour Application\n       |\n  SDK Client\n       | JSON-RPC\n  Copilot CLI (server mode)\n       |\n  GitHub (models, auth)\n```\n\nThe SDK manages the CLI process lifecycle automatically. All communication happens via JSON-RPC over stdio or TCP.\n\n## Resources\n\n- **GitHub Repository**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\n- **Getting Started Tutorial**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\u002Fblob\u002Fmain\u002Fdocs\u002Ftutorials\u002Ffirst-app.md\n- **GitHub MCP Server**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fgithub-mcp-server\n- **MCP Servers Directory**: https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers\n- **Cookbook**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\u002Ftree\u002Fmain\u002Fcookbook\n- **Samples**: https:\u002F\u002Fgithub.com\u002Fgithub\u002Fcopilot-sdk\u002Ftree\u002Fmain\u002Fsamples\n\n## Status\n\nThis SDK is in **Technical Preview** and may have breaking changes. Not recommended for production use yet.\n",{"name":5,"description":7},"main","61fa1fa8fcc63d6dbd2f07a75aeb8e214df5acfb","skills\u002Fcopilot-sdk",5344,"https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot","https:\u002F\u002Fawesome-copilot.github.com\u002F","https:\u002F\u002Fgithub.com\u002Fgithub","https:\u002F\u002Fgithub.com\u002Fabout","How people build software.","2026-11-13 02:05:36",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add github\u002Fawesome-copilot --skill copilot-sdk",{"tool":67,"command":68},"bunx","bunx skills add github\u002Fawesome-copilot --skill copilot-sdk",{"tool":70,"command":71},"pnpm","pnpm dlx skills add github\u002Fawesome-copilot --skill copilot-sdk","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fcopilot-sdk\u002FSKILL.md",true,[],[76,105,133,161,195,212],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":86,"publishedAt":46},"01M70KXZNX9ES38N2A8M58ZZMZ","supabase-rls-policies","Write, review, and test Supabase Row Level Security (RLS) policies so that one user cannot read or change another user's rows. Use when creating or changing tables, policies, views, or security definer functions in a Supabase project, when reviewing a migration that touches RLS, or when asked to prove user isolation with pgTAP tests that sign in as two users.","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fsupabase-rls-policies\u002FSKILL.md",[82,85],{"categoryNo":83,"categoryName":84,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[87,88,89,90,91,27,92,93,94,95,96,97,98,99,100,101,29,102,103,104],"supabase","rls","supabase rls","supabase rls policies","project","review","change","read","write","security","isolation","tables","as","tests","prove","users","functions","with",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":112,"publishedAt":46},"01M70KWA5YWXDV6V8DZ19E3T2Y","skill-distribution-audit","Audit a skill collection before release or investigate installer omissions, archived\u002Ftemplate leakage, duplicate identities, and manifest drift. Reconcile the intended public source set, distribution manifest, and actual discovery output for a specified consumer version. Includes a deterministic set-comparison helper.","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fskill-distribution-audit\u002FSKILL.md",[111],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132],"distribution","skill distribution audit","audit","SET","deterministic","installer","for","discovery","comparison","helper","manifest","version","collection","drift","output","investigate","duplicate","template","release","reconcile",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":137,"sourceHtmlUrl":138,"categories":139,"keywords":145,"publishedAt":46},"01M70KCJPFVW7PPQ49CC5R8JGK","logicapps-custom-code-net10-migration","Migrate Azure Logic Apps Standard local-function custom-code projects from .NET 8 to .NET 10. Use for legacy Logic Apps custom-code workspace upgrades, project\u002Fpackage configuration, custom-worker settings, publication, and integrated VS Code debugging. Not for ordinary .NET applications, standalone Azure Functions, Consumption workflows, or cloud deployment.","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Flogicapps-custom-code-net10-migration\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Flogicapps-custom-code-net10-migration\u002FSKILL.md",[140],{"categoryNo":141,"categoryName":142,"taxonomyType":143,"taxonomyTypeDesc":144},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[146,147,148,149,150,151,119,91,152,31,153,154,155,156,157,29,34,158,159,160],"custom","code","logicapps custom code net10 migration","migration","projects","standalone","deployment","local","azure","worker","upgrades","package","Legacy","debugging","workflows",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":165,"sourceHtmlUrl":166,"categories":167,"keywords":172,"publishedAt":46},"01M6AEBN37RQMXJ3298PEY7PG1","winmd-api-search","Find and explore Windows desktop APIs. Use when building features that need platform capabilities — camera, file access, notifications, UI controls, AI\u002FML, sensors, networking, etc. Discovers the right API for a task and retrieves full type details (methods, properties, events, enumeration values).","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fwinmd-api-search\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fwinmd-api-search\u002FSKILL.md",[168,171],{"categoryNo":169,"categoryName":170,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":141,"categoryName":142,"taxonomyType":143,"taxonomyTypeDesc":144},[173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,27,188,189,190,191,192,119,193,194],"winmd api search","search","api","windows","desktop","file access","enumeration","ui","ml","file","networking","capabilities","notifications","explore","access","features","full","camera","events","platform","methods","controls",{"skillNo":196,"name":197,"nameZh":6,"description":198,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":199,"licenseFileUrl":200,"sourceHtmlUrl":201,"categories":202,"keywords":208,"publishedAt":46},"01M6AE571R3SC1ZGE202B3NB5S","resemble-detect","Deepfake detection and media safety — detect AI-generated audio, images, video, and text, trace synthesis sources, apply watermarks, verify speaker identity, and analyze media intelligence using Resemble AI","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fresemble-detect\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fresemble-detect\u002FSKILL.md",[203,204,207],{"categoryNo":169,"categoryName":170,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":205,"categoryName":206,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[209,116,182,210,211],"resemble detect","https","identity",{"skillNo":213,"name":214,"nameZh":6,"description":215,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":199,"licenseFileUrl":216,"sourceHtmlUrl":217,"categories":218,"keywords":223,"publishedAt":46},"01M6AE30BSK2HCY4TQQ22Z8JRD","quality-playbook","Run a complete quality engineering audit on any codebase. Derives behavioral requirements from the code, generates spec-traced functional tests, runs a three-pass code review with regression tests, executes a multi-model spec audit (Council of Three), and produces a consolidated bug report with TDD-verified patches. Finds the 35% of real defects that structural code review alone cannot catch. Works with any language. Trigger on 'quality playbook', 'spec audit', 'Council of Three', 'fitness-to-purpose', or 'coverage theater'.","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fquality-playbook\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fgithub\u002Fawesome-copilot\u002Fblob\u002Fmain\u002Fskills\u002Fquality-playbook\u002FSKILL.md",[219,222],{"categoryNo":220,"categoryName":221,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[224,225,226,227,147,92,9,115,228,229,210,230,231,232,233,234,235,236,237,238,239,240,100,241,242,243,244],"playbook","quality playbook","quality","code review","tdd","run","report","spec","bug report","council","engineering","functional","spec audit","bug","verified","multi-model","three","coverage","model","regression","structural"]