-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Initial implementation of MCP Server and Awake tools #42762
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lei9444
wants to merge
29
commits into
main
Choose a base branch
from
leilzh/mcp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,183
−13
Open
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
b462b35
add mcp
lei9444 84d86b7
Merge branch 'main' of https://github.com/microsoft/PowerToys into le…
lei9444 250f51f
add identity
lei9444 6d2b982
update sparse app
lei9444 0243f57
update
lei9444 f32b253
update
lei9444 254927f
remove unused
lei9444 8c3649b
add new tool
lei9444 603dfca
update description
lei9444 a2b4318
add mcp
lei9444 9bbc2ff
update manifest
lei9444 005ae97
update the name
lei9444 c0d25aa
remove unused file
lei9444 402473a
remove backslash
lei9444 f8e0911
test add entrrpoint
lei9444 6ebc499
add entrypoint
lei9444 1fe58af
remove all
lei9444 cb91c93
Merge branch 'main' of https://github.com/microsoft/PowerToys into le…
lei9444 f6008bd
hide
lei9444 63b0e7b
Merge branch 'main' of https://github.com/microsoft/PowerToys into le…
lei9444 2cd8a5d
Merge branch 'leilzh/mcp' of https://github.com/microsoft/PowerToys i…
lei9444 0520463
add gpo
lei9444 97bb0b5
Merge branch 'main' of https://github.com/microsoft/PowerToys into le…
lei9444 2572598
set false
lei9444 63475ff
Merge branch 'main' of https://github.com/microsoft/PowerToys into le…
lei9444 f57c031
add ref
lei9444 fffb6ce
update the notice.md
lei9444 32d102b
add telemetry
lei9444 e0bf663
clean config when set awak
lei9444 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -976,6 +976,7 @@ maxversiontested | |
| mber | ||
| MBM | ||
| MBR | ||
| mcp | ||
| MDICHILD | ||
| MDL | ||
| mdtext | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
| <Import Project="..\Common.Dotnet.CsWinRT.props" /> | ||
| <Import Project="..\Common.SelfContained.props" /> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <RootNamespace>PowerToys.McpServer</RootNamespace> | ||
|
||
| <AssemblyName>PowerToys.McpServer</AssemblyName> | ||
| <Nullable>enable</Nullable> | ||
| <OutputPath>..\..\$(Platform)\$(Configuration)</OutputPath> | ||
| <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> | ||
| <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <ApplicationManifest>PowerToys.McpServer.dev.manifest</ApplicationManifest> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup Condition="'$(CIBuild)'=='true'"> | ||
| <ApplicationManifest>PowerToys.McpServer.prod.manifest</ApplicationManifest> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.Extensions.Hosting" /> | ||
| <PackageReference Include="ModelContextProtocol" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <FrameworkReference Include="Microsoft.WindowsDesktop.App" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\settings-ui\Settings.UI.Library\Settings.UI.Library.csproj" /> | ||
| <ProjectReference Include="..\common\ManagedCommon\ManagedCommon.csproj" /> | ||
| <ProjectReference Include="..\common\ManagedTelemetry\Telemetry\ManagedTelemetry.csproj" /> | ||
| <ProjectReference Include="..\common\GPOWrapperProjection\GPOWrapperProjection.csproj" /> | ||
| </ItemGroup> | ||
| </Project> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <?xml version="1.0" encoding="utf-8"?> | ||
|
||
| <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> | ||
| <assemblyIdentity version="1.0.0.0" name="PowerToys.McpServer.app" /> | ||
| <msix xmlns="urn:schemas-microsoft-com:msix.v1" | ||
| publisher="CN=PowerToys Dev, O=PowerToys, L=Redmond, S=Washington, C=US" | ||
| packageName="Microsoft.PowerToys.SparseApp" | ||
| applicationId="PowerToys.McpServer" /> | ||
| </assembly> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <?xml version="1.0" encoding="utf-8"?> | ||
|
||
| <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> | ||
| <assemblyIdentity version="1.0.0.0" name="PowerToys.McpServer.app" /> | ||
| <msix xmlns="urn:schemas-microsoft-com:msix.v1" | ||
| publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" | ||
| packageName="Microsoft.PowerToys.SparseApp" | ||
| applicationId="PowerToys.McpServer" /> | ||
| </assembly> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| // Copyright (c) Microsoft Corporation | ||
|
||
| // The Microsoft Corporation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| using System; | ||
| using System.IO; | ||
| using System.Threading.Tasks; | ||
| using ManagedCommon; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.PowerToys.Telemetry; | ||
| using ModelContextProtocol.Server; | ||
| using PowerToys.GPOWrapperProjection; | ||
| using PowerToys.McpServer.Telemetry.Events; | ||
| using PowerToys.McpServer.Tools; | ||
| using GpoProjection = PowerToys.GPOWrapperProjection.GPOWrapper; | ||
|
|
||
| namespace PowerToys.McpServer | ||
| { | ||
| internal sealed class Program | ||
| { | ||
| private static async Task<int> Main(string[] args) | ||
| { | ||
| // Initialize PowerToys logger | ||
| // Logger.InitializeLogger expects path relative to Constants.AppDataPath() | ||
| // which already points to LocalAppData\Microsoft\PowerToys | ||
| string logPath = Path.Combine("McpServer", "Logs"); | ||
| Logger.InitializeLogger(logPath); | ||
| Logger.LogInfo("Starting PowerToys MCP Server with official SDK"); | ||
|
|
||
| try | ||
| { | ||
| var mcpGpoState = GpoProjection.GetConfiguredMcpServerEnabledValue(); | ||
| if (mcpGpoState == GpoRuleConfigured.Disabled) | ||
| { | ||
| PowerToysTelemetry.Log.WriteEvent(new McpServerStartFailedEvent | ||
| { | ||
| Reason = "BlockedByPolicy", | ||
| }); | ||
| const string policyMessage = "MCP server launch blocked by Group Policy."; | ||
| Logger.LogWarning(policyMessage); | ||
| Console.Error.WriteLine(policyMessage); | ||
| return 0; | ||
| } | ||
|
|
||
| var builder = Host.CreateApplicationBuilder(args); | ||
|
|
||
| // Configure all logs to go to stderr (required for MCP protocol) | ||
| builder.Logging.AddConsole(consoleLogOptions => | ||
| { | ||
| consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace; | ||
| }); | ||
|
|
||
| // Register MCP server with stdio transport and tools | ||
| builder.Services | ||
| .AddMcpServer() | ||
| .WithStdioServerTransport() | ||
| .WithToolsFromAssembly(); | ||
|
|
||
| using var host = builder.Build(); | ||
|
|
||
| PowerToysTelemetry.Log.WriteEvent(new McpServerStartedEvent()); | ||
|
|
||
| Logger.LogInfo("Building and running MCP host..."); | ||
| await host.RunAsync(); | ||
| Logger.LogInfo("MCP server shutdown complete"); | ||
|
|
||
| return 0; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| PowerToysTelemetry.Log.WriteEvent(new McpServerStartFailedEvent | ||
| { | ||
| Reason = BuildFailureReason(ex), | ||
| }); | ||
| Logger.LogError("Fatal error in MCP server", ex); | ||
| return 1; | ||
| } | ||
| } | ||
|
|
||
| private static string BuildFailureReason(Exception ex) | ||
| { | ||
| string type = ex.GetType().FullName ?? "UnknownException"; | ||
| string message = ex.Message ?? string.Empty; | ||
| string combined = $"UnhandledException:{type}:{message}"; | ||
|
|
||
| const int maxLength = 256; | ||
| if (combined.Length <= maxLength) | ||
| { | ||
| return combined; | ||
| } | ||
|
|
||
| return combined.Substring(0, maxLength); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # PowerToys Model Context Protocol Server | ||
|
||
|
|
||
| This module hosts a standalone Model Context Protocol (MCP) server that exposes PowerToys functionality to MCP-compliant AI agents. The server is built as a .NET 9 console application that implements the MCP specification using the official ModelContextProtocol SDK. | ||
|
|
||
| ## Project Structure | ||
|
|
||
| - **Program.cs**: Main entry point that configures the MCP server with stdio transport | ||
| - **Tools/AwakeTools.cs**: Implementation of Awake-related MCP tools | ||
| - **PowerToys.McpServer.csproj**: .NET 9 project configuration with MCP dependencies | ||
|
|
||
| ## Dependencies | ||
|
|
||
| - **Microsoft.Extensions.Hosting**: For hosting infrastructure and dependency injection | ||
| - **ModelContextProtocol**: Official MCP SDK for .NET | ||
| - **PowerToys Settings Library**: Integration with PowerToys settings system | ||
| - **ManagedCommon**: PowerToys logging and utilities | ||
|
|
||
| ## Available Tools | ||
|
|
||
| | Tool Name | Description | Parameters | Module | | ||
| |-----------|-------------|------------|--------| | ||
| | `GetAwakeStatus` | Returns the current Awake configuration (mode, timers, display policy) | None | Awake | | ||
| | `SetAwakePassive` | Set Awake to passive mode (allow system to sleep normally) | None | Awake | | ||
| | `SetAwakeIndefinite` | Set Awake to indefinite mode (keep system awake until manually changed) | `keepDisplayOn` (bool), `force` (bool) | Awake | | ||
| | `SetAwakeTimed` | Set Awake to timed mode (keep system awake for a specific duration) | `durationSeconds` (int), `keepDisplayOn` (bool), `force` (bool) | Awake | | ||
|
|
||
| ## Building and Running | ||
|
|
||
| ### Prerequisites | ||
| - .NET 9 SDK | ||
| - Visual Studio 2022 (recommended) or VS Code with C# extension | ||
|
|
||
| ### Build | ||
| ```bash | ||
| # From PowerToys root directory | ||
| msbuild src/McpServer/PowerToys.McpServer.csproj /p:Platform=x64 /p:Configuration=Debug | ||
|
|
||
| # Or using dotnet CLI | ||
| cd src/McpServer | ||
| dotnet build -c Debug | ||
| ``` | ||
|
|
||
| ### Run the Server | ||
| The executable is built to `x64\Debug\PowerToys.McpServer.exe`. The server communicates over standard input/output using MCP framing (`Content-Length` header followed by JSON). | ||
|
|
||
| **Example MCP Client Session:** | ||
| 1. Client sends `initialize` request with MCP version and capabilities | ||
| 2. Client calls `tools/list` to discover available PowerToys tools | ||
| 3. Client invokes `tools/call` with the desired tool name and arguments | ||
| 4. Server responds with tool execution results or errors | ||
|
|
||
| The server will remain active until the process is terminated or a `shutdown` request is received. | ||
|
|
||
| ### Logging | ||
| - Application logs are written to `%LOCALAPPDATA%\Microsoft\PowerToys\McpServer\Logs\` | ||
| - MCP protocol logs are sent to stderr (required by MCP specification) | ||
|
|
||
| ## Architecture | ||
|
|
||
| The server uses the official ModelContextProtocol .NET SDK and follows these patterns: | ||
|
|
||
| - **Tool Discovery**: Tools are automatically discovered using `WithToolsFromAssembly()` | ||
| - **Tool Attributes**: Methods marked with `[McpServerTool]` and `[Description]` are exposed as MCP tools | ||
| - **Parameter Binding**: Method parameters are automatically bound from MCP tool call arguments | ||
| - **Error Handling**: Exceptions are caught and returned as MCP error responses | ||
| - **Settings Integration**: Uses PowerToys settings system for configuration persistence | ||
|
|
||
| ## Adding New Module Tools | ||
|
|
||
| 1. Create a new static class in the `Tools/` directory (e.g., `FancyZonesTools.cs`) | ||
| 2. Mark the class with `[McpServerToolType]` attribute | ||
| 3. Implement static methods with `[McpServerTool]` and `[Description]` attributes: | ||
| ```csharp | ||
| [McpServerToolType] | ||
| public static class MyModuleTools | ||
| { | ||
| [McpServerTool] | ||
| [Description("Description of what this tool does")] | ||
| public static JsonObject MyTool( | ||
| [Description("Parameter description")] string parameter) | ||
| { | ||
| // Implementation here | ||
| return new JsonObject(); | ||
| } | ||
| } | ||
| ``` | ||
| 4. Follow existing patterns in `AwakeTools.cs` for: | ||
| - Settings integration using `SettingsUtils` | ||
| - Logging using `Logger.LogInfo/LogError` | ||
| - Error handling and response formatting | ||
| - PowerToys process detection and module status checks | ||
|
|
||
| ## Integration with PowerToys | ||
|
|
||
| The MCP server integrates with PowerToys through: | ||
|
|
||
| - **Settings System**: Uses the same settings files as the main PowerToys application | ||
| - **Process Management**: Detects and interacts with running PowerToys processes | ||
| - **Module Status**: Checks if specific PowerToys modules are enabled | ||
| - **Logging**: Uses PowerToys logging infrastructure for troubleshooting | ||
|
|
||
| Refer to the PowerToys developer documentation for build and packaging instructions. | ||
25 changes: 25 additions & 0 deletions
25
src/McpServer/Telemetry/Events/McpServerStartFailedEvent.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| // Copyright (c) Microsoft Corporation | ||
| // The Microsoft Corporation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Diagnostics.Tracing; | ||
| using Microsoft.PowerToys.Telemetry; | ||
| using Microsoft.PowerToys.Telemetry.Events; | ||
|
|
||
| namespace PowerToys.McpServer.Telemetry.Events | ||
| { | ||
| [EventData] | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] | ||
| public class McpServerStartFailedEvent : EventBase, IEvent | ||
| { | ||
| public McpServerStartFailedEvent() | ||
| { | ||
| EventName = "McpServer_StartFailed"; | ||
| } | ||
|
|
||
| public string Reason { get; set; } = string.Empty; | ||
|
|
||
| public PartA_PrivTags PartA_PrivTags => PartA_PrivTags.ProductAndServicePerformance; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| // Copyright (c) Microsoft Corporation | ||
| // The Microsoft Corporation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Diagnostics.Tracing; | ||
| using Microsoft.PowerToys.Telemetry; | ||
| using Microsoft.PowerToys.Telemetry.Events; | ||
|
|
||
| namespace PowerToys.McpServer.Telemetry.Events | ||
| { | ||
| [EventData] | ||
| [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] | ||
| public class McpServerStartedEvent : EventBase, IEvent | ||
| { | ||
| public McpServerStartedEvent() | ||
| { | ||
| EventName = "McpServer_Started"; | ||
| } | ||
|
|
||
| public PartA_PrivTags PartA_PrivTags => PartA_PrivTags.ProductAndServiceUsage; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.