Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0" PrivateAssets="all" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" PrivateAssets="all" />
<PackageVersion Include="Microsoft.CodeAnalysis.Common" Version="5.3.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.5.1" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="10.0.300" PrivateAssets="All" />
<PackageVersion Include="Microsoft.VisualStudio.Interop" Version="17.14.40260" />
<PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.275" />
<PackageVersion Include="ModelContextProtocol" Version="1.1.0" />
<PackageVersion Include="MSTest.TestAdapter" Version="4.2.2" />
<PackageVersion Include="MSTest.TestFramework" Version="4.2.3" />
<PackageVersion Include="System.CommandLine" Version="2.0.8" />
Expand Down
22 changes: 22 additions & 0 deletions XAMLTest.Mcp/.mcp/server.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-10-17/server.schema.json",
"description": "<your description here>",
"name": "io.github.<your GitHub username here>/<your repo name>",
"version": "0.1.0-beta",
"packages": [
{
"registryType": "nuget",
"identifier": "<your package ID here>",
"version": "0.1.0-beta",
"transport": {
"type": "stdio"
},
"packageArguments": [],
"environmentVariables": []
}
],
"repository": {
"url": "https://github.com/<your GitHub username here>/<your repo name>",
"source": "github"
}
}
57 changes: 57 additions & 0 deletions XAMLTest.Mcp/AppServiceManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

using XamlTest;

namespace XAMLTest.Mcp;

public sealed class AppServiceManager : IAsyncDisposable
{
private Dictionary<string, IApp> RunningApps { get; } = [];

public async ValueTask DisposeAsync()
{
List<IApp> apps;
lock (RunningApps)
{
apps = [.. RunningApps.Values];
RunningApps.Clear();
}
await Task.WhenAll(apps.Select(app => app.DisposeAsync().AsTask()));
}

public bool TryGetApp(string appId, [NotNullWhen(true)] out IApp? app)
{
lock (RunningApps)
{
return RunningApps.TryGetValue(appId, out app);
}
}

public async Task<bool> ShutdownApp(string appId)
{
IApp? app;
lock (RunningApps)
{
if (RunningApps.TryGetValue(appId, out app))
{
RunningApps.Remove(appId);
}
}
if (app is not null)
{
await app.DisposeAsync();
return true;
}
return false;
}

public string RegisterApp(IApp app)
{
string appId;
lock (RunningApps)
{
appId = $"app{RunningApps.Count + 1}";
RunningApps[appId] = app;
}
return appId;
}
}
20 changes: 20 additions & 0 deletions XAMLTest.Mcp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using XAMLTest.Mcp;

var builder = Host.CreateApplicationBuilder(args);

// Configure all logs to go to stderr (stdout is used for the MCP protocol messages).
builder.Logging.AddConsole(o => o.LogToStandardErrorThreshold = LogLevel.Trace);

builder.Services.AddSingleton<AppServiceManager>();

// Add the MCP services: the transport to use (stdio) and the tools to register.
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();

var app = builder.Build();
await app.RunAsync();
98 changes: 98 additions & 0 deletions XAMLTest.Mcp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# MCP Server

This README was created using the C# MCP server project template.
It demonstrates how you can easily create an MCP server using C# and publish it as a NuGet package.

The MCP server is built as a self-contained application and does not require the .NET runtime to be installed on the target machine.
However, since it is self-contained, it must be built for each target platform separately.
By default, the template is configured to build for:
* `win-x64`
* `win-arm64`
* `osx-arm64`
* `linux-x64`
* `linux-arm64`
* `linux-musl-x64`

If your users require more platforms to be supported, update the list of runtime identifiers in the project's `<RuntimeIdentifiers />` element.

See [aka.ms/nuget/mcp/guide](https://aka.ms/nuget/mcp/guide) for the full guide.

Please note that this template is currently in an early preview stage. If you have feedback, please take a [brief survey](http://aka.ms/dotnet-mcp-template-survey).

## Checklist before publishing to NuGet.org

- Test the MCP server locally using the steps below.
- Update the package metadata in the .csproj file, in particular the `<PackageId>`.
- Update `.mcp/server.json` to declare your MCP server's inputs.
- See [configuring inputs](https://aka.ms/nuget/mcp/guide/configuring-inputs) for more details.
- Pack the project using `dotnet pack`.

The `bin/Release` directory will contain the package file (.nupkg), which can be [published to NuGet.org](https://learn.microsoft.com/nuget/nuget-org/publish-a-package).

## Developing locally

To test this MCP server from source code (locally) without using a built MCP server package, you can configure your IDE to run the project directly using `dotnet run`.

```json
{
"servers": {
"XAMLTest.Mcp": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"<PATH TO PROJECT DIRECTORY>"
]
}
}
}
```

## Testing the MCP Server

Once configured, you can ask Copilot Chat for a random number, for example, `Give me 3 random numbers`. It should prompt you to use the `get_random_number` tool on the `XAMLTest.Mcp` MCP server and show you the results.

## Publishing to NuGet.org

1. Run `dotnet pack -c Release` to create the NuGet package
2. Publish to NuGet.org with `dotnet nuget push bin/Release/*.nupkg --api-key <your-api-key> --source https://api.nuget.org/v3/index.json`

## Using the MCP Server from NuGet.org

Once the MCP server package is published to NuGet.org, you can configure it in your preferred IDE. Both VS Code and Visual Studio use the `dnx` command to download and install the MCP server package from NuGet.org.

- **VS Code**: Create a `<WORKSPACE DIRECTORY>/.vscode/mcp.json` file
- **Visual Studio**: Create a `<SOLUTION DIRECTORY>\.mcp.json` file

For both VS Code and Visual Studio, the configuration file uses the following server definition:

```json
{
"servers": {
"XAMLTest.Mcp": {
"type": "stdio",
"command": "dnx",
"args": [
"<your package ID here>",
"--version",
"<your package version here>",
"--yes"
]
}
}
}
```

## More information

.NET MCP servers use the [ModelContextProtocol](https://www.nuget.org/packages/ModelContextProtocol) C# SDK. For more information about MCP:

- [Official Documentation](https://modelcontextprotocol.io/)
- [Protocol Specification](https://spec.modelcontextprotocol.io/)
- [GitHub Organization](https://github.com/modelcontextprotocol)

Refer to the VS Code or Visual Studio documentation for more information on configuring and using MCP servers:

- [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp-servers)
- [Use MCP servers in Visual Studio (Preview)](https://learn.microsoft.com/visualstudio/ide/mcp-servers)
47 changes: 47 additions & 0 deletions XAMLTest.Mcp/SharedStrings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace XAMLTest.Mcp;

public static class SharedStrings
{
public const string AppIdDescription = "The XAMLTest application id";

public const string XamlSnippetDescription =
"""
The XAML snippet to render in a WPF Window.
This should only include the content inside the Window tags.
""";

public const string ElementQueryDescription =
"""
A query string to find a visual element. Supported formats:
~<Name> - Search by element Name (default if no prefix).
/<TypeName> - Search by type name (e.g. /Button). Supports base types and [Index] suffix (e.g. /Button[1]).
.<PropertyName> - Navigate to a property value of the previous element.
[<Property>=<Value>] - Search for an element where the property matches the value.
Queries can be chained (e.g. /StackPanel/Button[0]).
""";

public const string PropertyNameDescription = "The name of the property to access (e.g. Content, Text, IsEnabled, Width).";

public const string InputActionsJsonDescription =
"""
A JSON array of ordered interaction actions to execute on the target element.
Each action must include a `type` property. Supported action types:
- focus
- delay (milliseconds)
- mouse_move_to_element (position, xOffset, yOffset)
- mouse_move_relative (xOffset, yOffset)
- mouse_move_absolute (x, y)
- mouse_button_down (button: left|right|middle)
- mouse_button_up (button: left|right|middle)
- mouse_click (button, count, position, xOffset, yOffset, clickDelayMs)
- keyboard_text (text)
- keyboard_keys (keys: string[])
Example:
[
{ "type": "focus" },
{ "type": "mouse_click", "button": "left", "position": "Center" },
{ "type": "keyboard_text", "text": "Hello world" },
{ "type": "keyboard_keys", "keys": ["Enter"] }
]
""";
}
120 changes: 120 additions & 0 deletions XAMLTest.Mcp/Tools/AppTools.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.ComponentModel;
using XamlTest;
using XAMLTest.Mcp;

[McpServerToolType]
internal class AppTools(AppServiceManager appServiceManager) : BaseTools
{
[McpServerTool]
[Description("""
Starts a new WPF application using the provided application XAML, referenced assemblies, and creates a window with the specified XAML.
This return the XAMLTest Id of the application.
""")]
public async Task<string> StartApp(
[Description("""
The full XAML for a WPF window, including its contents.
""")] string windowXaml,
[Description("""
This is the raw application XAML to initialize the WPF app with.
""")] string? appXaml = null,
[Description("""
The full path to any additional assemblies to load into the application domain.
""")] string?[]? additionalAssemblies = null)
{
var app = await App.StartRemote(new AppOptions()
{
AllowVisualStudioDebuggerAttach = false,
MinimizeOtherWindows = false
});

if (!string.IsNullOrWhiteSpace(appXaml))
{
string[] assemblies = [];
if (additionalAssemblies is not null)
{
assemblies = additionalAssemblies.Where(x => x is not null).ToArray()!;
}
await app.Initialize(appXaml, assemblies);
}
else
{
await app.InitializeWithDefaults();
}

var _ = await app.CreateWindow(windowXaml);

return appServiceManager.RegisterApp(app);
}

[McpServerTool]
[Description("""
Starts a new WPF application and creates a window with the specified XAML snippet as its content.
This return the XAMLTest Id of the application.
""")]
public async Task<string> StartAppWithXamlSnippet(
[Description(SharedStrings.XamlSnippetDescription)] string xamlSnippet)
{
var app = await App.StartRemote(new AppOptions()
{
AllowVisualStudioDebuggerAttach = false,
MinimizeOtherWindows = false
});

await app.InitializeWithDefaults();

var _ = await app.CreateWindowWithContent(xamlSnippet);

return appServiceManager.RegisterApp(app);
}

[McpServerTool]
[Description("""
Shuts down the specified XAML Test application.
""")]
public async Task<CallToolResult> ShutdownApp(
[Description(SharedStrings.AppIdDescription)] string appId)
{
return (await appServiceManager.ShutdownApp(appId))
? Success()
: Failure($"No known app with id '{appId}' is running");
}

[McpServerTool]
[Description("""
Captures a screenshot of the specified XAML Test application and returns it as inline BMP image content.
""")]
public async Task<CallToolResult> SaveScreenshot(string appId,
[Description("Optional file path locations for where to same the image")]
string? filePath = null)
{
if (!appServiceManager.TryGetApp(appId, out var app))
{
return Failure($"No known app with id '{appId}' is running");
}

IImage screenshot = await app.GetScreenshot();

using MemoryStream bmpStream = new();
await screenshot.Save(bmpStream);
bmpStream.Position = 0;
byte[] bmpBytes = bmpStream.ToArray();

if (filePath is not null)
{
await File.WriteAllBytesAsync(filePath, bmpBytes);
}

return new CallToolResult
{
IsError = false,
Content =
[
new TextContentBlock { Text = $"Screenshot for {appId}:" },
ImageContentBlock.FromBytes(bmpBytes, "image/bmp")
]
};
}
}

Loading
Loading