diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..a2ef2565b --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,17 @@ + + + 13 + true + enable + enable + false + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)')) + trx%3bLogFileName=$(MSBuildProjectName).$(TargetFramework).$(OS).trx + $(RepoRoot)/artifacts/TestResults + false + + + + true + + \ No newline at end of file diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 000000000..b57c38b36 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,36 @@ + + + true + 9.3.0-preview.1.25161.3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ModelContextProtocol.sln b/ModelContextProtocol.sln index 16a1c4ef1..8bd8f6273 100644 --- a/ModelContextProtocol.sln +++ b/ModelContextProtocol.sln @@ -24,12 +24,18 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspNetCoreSseServer", "samples\AspNetCoreSseServer\AspNetCoreSseServer.csproj", "{B6F42305-423F-56FF-090F-B7263547F924}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A2F1F52A-9107-4BF8-8C3F-2F6670E7D0AD}" + ProjectSection(SolutionItems) = preProject + src\Directory.Build.props = src\Directory.Build.props + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B6FB2B28-D5DE-4654-BE9A-45E305DE4852}" ProjectSection(SolutionItems) = preProject + Directory.Build.props = Directory.Build.props global.json = global.json LICENSE = LICENSE + logo.png = logo.png README.MD = README.MD + version.json = version.json EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{1288ADA5-1BF1-4A7F-A33E-9EA29097AA40}" diff --git a/logo.png b/logo.png new file mode 100644 index 000000000..89dafab9f Binary files /dev/null and b/logo.png differ diff --git a/samples/AspNetCoreSseServer/AspNetCoreSseServer.csproj b/samples/AspNetCoreSseServer/AspNetCoreSseServer.csproj index 601af56ee..cd534dfe1 100644 --- a/samples/AspNetCoreSseServer/AspNetCoreSseServer.csproj +++ b/samples/AspNetCoreSseServer/AspNetCoreSseServer.csproj @@ -11,7 +11,7 @@ - + diff --git a/samples/TestServerWithHosting/TestServerWithHosting.csproj b/samples/TestServerWithHosting/TestServerWithHosting.csproj index 3cd5eda74..137d753bb 100644 --- a/samples/TestServerWithHosting/TestServerWithHosting.csproj +++ b/samples/TestServerWithHosting/TestServerWithHosting.csproj @@ -8,11 +8,11 @@ - - - - - + + + + + diff --git a/samples/anthropic/tools/ToolsConsole/AnthropicToolsConsole.csproj b/samples/anthropic/tools/ToolsConsole/AnthropicToolsConsole.csproj index e0924d4a3..cd611955d 100644 --- a/samples/anthropic/tools/ToolsConsole/AnthropicToolsConsole.csproj +++ b/samples/anthropic/tools/ToolsConsole/AnthropicToolsConsole.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/samples/microsoft.extensions.ai/tools/ToolsConsole/MEAIToolsConsole.csproj b/samples/microsoft.extensions.ai/tools/ToolsConsole/MEAIToolsConsole.csproj index 6aeea6581..d04a44ed6 100644 --- a/samples/microsoft.extensions.ai/tools/ToolsConsole/MEAIToolsConsole.csproj +++ b/samples/microsoft.extensions.ai/tools/ToolsConsole/MEAIToolsConsole.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 000000000..1a1064e11 --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,25 @@ + + + + + https://github.com/modelcontextprotocol/csharp-sdk + https://github.com/modelcontextprotocol/csharp-sdk + git + ModelContextProtocol;mcp;ai;llm + MIT + logo.png + true + snupkg + $(RepoRoot)artifacts/ + true + + + + + + + + + + + \ No newline at end of file diff --git a/src/ModelContextProtocol/ModelContextProtocol.csproj b/src/ModelContextProtocol/ModelContextProtocol.csproj index 4e5b890e3..f1b5f6c5f 100644 --- a/src/ModelContextProtocol/ModelContextProtocol.csproj +++ b/src/ModelContextProtocol/ModelContextProtocol.csproj @@ -2,52 +2,39 @@ net8.0;netstandard2.0 - enable - enable - Latest - true - All + true + true + ModelContextProtocol + .NET SDK for the Model Context Protocol (MCP) + README.md true - - - ModelContextProtocol - .NET SDK for the Model Context Protocol (MCP) - https://github.com/modelcontextprotocol/csharp-sdk - https://github.com/modelcontextprotocol/csharp-sdk - git - ModelContextProtocol;mcp;ai;llm - README.md - MIT - - ModelContextProtocol - true - true - snupkg - - - - - - - + + + + + - - - + + + + + + + diff --git a/src/ModelContextProtocol/README.md b/src/ModelContextProtocol/README.md new file mode 100644 index 000000000..b2205768b --- /dev/null +++ b/src/ModelContextProtocol/README.md @@ -0,0 +1,177 @@ +# MCP C# SDK + +The official C# SDK for the [Model Context Protocol](https://modelcontextprotocol.io/), enabling .NET applications to connect to and interact with MCP clients and servers. + +> [!NOTE] +> This repo is still in preview, breaking changes can be introduced without prior notice. + +## About MCP + +The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). It enables secure integration between LLMs and various data sources and tools. + +For more information about MCP: +- [Official Documentation](https://modelcontextprotocol.io/) +- [Protocol Specification](https://spec.modelcontextprotocol.io/) +- [GitHub Organization](https://github.com/modelcontextprotocol) + +## Getting Started (Client) + +Then create a client and start using tools, or other capabilities, from the servers you configure: +```csharp +McpClientOptions options = new() +{ + ClientInfo = new() { Name = "TestClient", Version = "1.0.0" } +}; + +McpServerConfig config = new() +{ + Id = "everything", + Name = "Everything", + TransportType = TransportTypes.StdIo, + TransportOptions = new() + { + ["command"] = "npx", + ["arguments"] = "-y @modelcontextprotocol/server-everything", + } +}; + +var client = await McpClientFactory.CreateAsync(config, options); + +// Print the list of tools available from the server. +await foreach (var tool in client.ListToolsAsync()) +{ + Console.WriteLine($"{tool.Name} ({tool.Description})"); +} + +// Execute a tool (this would normally be driven by LLM tool invocations). +var result = await client.CallToolAsync( + "echo", + new() { ["message"] = "Hello MCP!" }, + CancellationToken.None); + +// echo always returns one and only one text content object +Console.WriteLine(result.Content.First(c => c.Type == "text").Text); +``` + +Note that you should pass CancellationToken objects suitable for your use case, to enable proper error handling, timeouts, etc. This example also does not paginate the tools list, which may be necessary for large tool sets. See the IntegrationTests project for an example of pagination, as well as examples of how to handle Prompts and Resources. + +It is also highly recommended that you pass a proper LoggerFactory instance to the factory constructor, to enable logging of MCP client operations. + +You can find samples demonstrating how to use ModelContextProtocol with an LLM SDK in the [samples](samples) directory, and also refer to the [IntegrationTests](test/ModelContextProtocol.IntegrationTests) project for more examples. + +Additional examples and documentation will be added as in the near future. + +Remember you can connect to any MCP server, not just ones created using ModelContextProtocol. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server. + +Tools can be exposed easily as `AIFunction` instances so that they are immediately usable with `IChatClient`s. +```csharp +// Get available functions. +IList tools = await client.GetAIFunctionsAsync(); + +// Call the chat client using the tools. +IChatClient chatClient = ...; +var response = await chatClient.GetResponseAsync( + "your prompt here", + new() + { + Tools = [.. tools], + }); +``` + +## Getting Started (Server) + +Here is an example of how to create an MCP server and register all tools from the current application. +It includes a simple echo tool as an example (this is included in the same file here for easy of copy and paste, but it needn't be in the same file... +the employed overload of `WithTools` examines the current assembly for classes with the `McpToolType` attribute, and registers all methods with the +`McpTool` attribute as tools.) + +```csharp +using ModelContextProtocol; +using ModelContextProtocol.Server; +using Microsoft.Extensions.Hosting; +using System.ComponentModel; + +var builder = Host.CreateEmptyApplicationBuilder(settings: null); +builder.Services + .AddMcpServer() + .WithStdioServerTransport() + .WithTools(); +await builder.Build().RunAsync(); + +[McpToolType] +public static class EchoTool +{ + [McpTool, Description("Echoes the message back to the client.")] + public static string Echo(string message) => $"hello {message}"; +} +``` + +More control is also available, with fine-grained control over configuring the server and how it should handle client requests. For example: +```csharp +using ModelContextProtocol.Protocol.Transport; +using ModelContextProtocol.Protocol.Types; +using ModelContextProtocol.Server; +using Microsoft.Extensions.Logging.Abstractions; + +McpServerOptions options = new() +{ + ServerInfo = new() { Name = "MyServer", Version = "1.0.0" }, + Capabilities = new() + { + Tools = new() + { + ListToolsHandler = async (request, cancellationToken) => + { + return new ListToolsResult() + { + Tools = + [ + new Tool() + { + Name = "echo", + Description = "Echoes the input back to the client.", + InputSchema = new JsonSchema() + { + Type = "object", + Properties = new Dictionary() + { + ["message"] = new JsonSchemaProperty() { Type = "string", Description = "The input to echo back." } + } + }, + } + ] + }; + }, + + CallToolHandler = async (request, cancellationToken) => + { + if (request.Params?.Name == "echo") + { + if (request.Params.Arguments?.TryGetValue("message", out var message) is not true) + { + throw new McpServerException("Missing required argument 'message'"); + } + + return new CallToolResponse() + { + Content = [new Content() { Text = $"Echo: {message}", Type = "text" }] + }; + } + + throw new McpServerException($"Unknown tool: '{request.Params?.Name}'"); + }, + } + }, +}; + +await using IMcpServer server = McpServerFactory.Create(new StdioServerTransport("MyServer"), options); + +await server.StartAsync(); + +// Run until process is stopped by the client (parent process) +await Task.Delay(Timeout.Infinite); +``` + +## License + +This project is licensed under the [MIT License](LICENSE). diff --git a/tests/ModelContextProtocol.TestServer/ModelContextProtocol.TestServer.csproj b/tests/ModelContextProtocol.TestServer/ModelContextProtocol.TestServer.csproj index d8826c649..67dc6a197 100644 --- a/tests/ModelContextProtocol.TestServer/ModelContextProtocol.TestServer.csproj +++ b/tests/ModelContextProtocol.TestServer/ModelContextProtocol.TestServer.csproj @@ -10,10 +10,10 @@ - - - - + + + + diff --git a/tests/ModelContextProtocol.TestSseServer/ModelContextProtocol.TestSseServer.csproj b/tests/ModelContextProtocol.TestSseServer/ModelContextProtocol.TestSseServer.csproj index 77b3ccdaf..544be2e0d 100644 --- a/tests/ModelContextProtocol.TestSseServer/ModelContextProtocol.TestSseServer.csproj +++ b/tests/ModelContextProtocol.TestSseServer/ModelContextProtocol.TestSseServer.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj b/tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj index bd65b031f..6d31fac76 100644 --- a/tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj +++ b/tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj @@ -12,18 +12,14 @@ - - - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/version.json b/version.json new file mode 100644 index 000000000..15f55420b --- /dev/null +++ b/version.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/main/src/NerdBank.GitVersioning/version.schema.json", + "version": "0.1.0-preview", + "publicReleaseRefSpec": [ + "^refs/heads/main$", + "^refs/heads/v\\d+(?:\\.\\d+)?$", + "^refs/tags/v\\d+(?:\\.\\d+)?" + ] +} \ No newline at end of file