├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml └── workflows │ ├── build.yml │ └── release.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── MCPSharp.Example.OllamaChatCLI ├── MCPClientPool.cs ├── MCPSharp.Example.OllamaChatCLI.csproj ├── Program.cs └── config.json ├── MCPSharp.Example ├── ComplicatedObject.cs ├── MCPDev.cs ├── MCPSharp.Example.csproj └── Program.cs ├── MCPSharp.ExternalExample ├── ExternalTool.cs └── MCPSharp.Example.Import.csproj ├── MCPSharp.Test ├── AIFunctionAbstractionTests.cs ├── ClientTests.cs ├── GlobalSuppressions.cs ├── MCPSharp.Test.csproj ├── MSTestSettings.cs ├── SSETransportTests.cs └── STDIOTransportTests.cs ├── MCPSharp.sln ├── MCPSharp ├── Attributes │ ├── McpFunctionAttribute.cs │ ├── McpParameterAttribute.cs │ ├── McpResourceAttribute.cs │ └── McpToolAttribute.cs ├── Core │ ├── MCPClient.cs │ ├── MCPFunction.cs │ ├── MCPServer.cs │ ├── ServerRpcTarget.cs │ ├── Tools │ │ ├── ToolHandler.cs │ │ └── ToolManager.cs │ └── Transport │ │ ├── DuplexPipe.cs │ │ └── SSE │ │ ├── HttpPostStream.cs │ │ ├── ServerSentEventsService.cs │ │ └── SseClient.cs ├── GlobalSuppressions.cs ├── MCPSharp.csproj ├── Model │ ├── Capabilities │ │ ├── ClientCapabilities.cs │ │ └── ServerCapabilities.cs │ ├── Content │ │ └── TextContent.cs │ ├── Implementation.cs │ ├── MetaData.cs │ ├── Parameters │ │ ├── InitializationParameters.cs │ │ └── ToolCallParameters.cs │ ├── Results │ │ ├── CallToolResult.cs │ │ ├── InitializeResult.cs │ │ ├── ListToolsResult.cs │ │ ├── PromptListResult.cs │ │ ├── ResourcesListResult.cs │ │ └── ToolsListResult.cs │ ├── Schemas │ │ ├── InputSchema.cs │ │ └── ParameterSchema.cs │ └── Tool.cs ├── XmlDocumentationExtensions.cs └── icon.png ├── README.md ├── SECURITY.md └── banner.svg /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "nuget" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ development, master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Setup .NET 17 | uses: actions/setup-dotnet@v4 18 | with: 19 | dotnet-version: '9.0.x' 20 | 21 | - name: Restore dependencies 22 | run: dotnet restore 23 | 24 | - name: Build 25 | run: dotnet build --no-restore --configuration Release 26 | 27 | - name: Test 28 | run: dotnet test --no-build --configuration Release --verbosity normal 29 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release to NuGet 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: 'Version number (e.g., 1.0.0)' 8 | required: true 9 | type: string 10 | 11 | jobs: 12 | build-and-publish: 13 | runs-on: ubuntu-latest 14 | if: github.ref == 'refs/heads/master' 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v4 21 | with: 22 | dotnet-version: '9.0.x' 23 | 24 | - name: Restore dependencies 25 | run: dotnet restore MCPSharp/MCPSharp.csproj 26 | 27 | - name: Build 28 | run: dotnet build MCPSharp/MCPSharp.csproj --no-restore --configuration Release 29 | 30 | - name: Test 31 | run: dotnet test MCPSharp/MCPSharp.csproj --no-build --configuration Release --verbosity normal 32 | 33 | - name: Pack 34 | run: dotnet pack MCPSharp/MCPSharp.csproj --no-build --configuration Release -p:PackageVersion=${{ github.event.inputs.version }} --output nupkgs 35 | 36 | - name: Push to NuGet 37 | run: dotnet nuget push /home/runner/work/MCPSharp/MCPSharp/nupkgs/MCPSharp.${{ github.event.inputs.version }}.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json 38 | 39 | - name: Publish Github release 40 | id: create_release 41 | uses: actions/create-release@v1 42 | env: 43 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 44 | with: 45 | tag_name: ${{ github.event.inputs.version }} 46 | release_name: MCPSharp ${{ github.event.inputs.version }} 47 | body: | 48 | Release of MCPSharp version ${{ github.event.inputs.version }} 49 | draft: false 50 | prerelease: false 51 | 52 | - name: Upload Release Asset 53 | uses: actions/upload-release-asset@v1 54 | env: 55 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 56 | with: 57 | upload_url: ${{ steps.create_release.outputs.upload_url }} 58 | asset_path: /home/runner/work/MCPSharp/MCPSharp/nupkgs/MCPSharp.${{ github.event.inputs.version }}.nupkg 59 | asset_name: MCPSharp.${{ github.event.inputs.version }}.nupkg 60 | asset_content_type: application/zip 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd 364 | /MCPSharp/data.txt 365 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | afrise@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to MCPSharp 2 | 3 | ## Introduction 4 | 5 | Thank you for your interest in contributing to MCPSharp! This document outlines the process for contributing to the project. 6 | 7 | ## Code of Conduct 8 | 9 | By participating in this project, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md). 10 | 11 | ## How Can I Contribute? 12 | 13 | ### Reporting Bugs 14 | 15 | If you find a bug, please open an issue and include detailed steps to reproduce the problem. Ensure the issue has not already been reported by searching the [issues list](https://github.com/afrise/MCPSharp/issues). 16 | 17 | ### Suggesting Enhancements 18 | 19 | We welcome suggestions for new features or improvements. Please submit an issue with: 20 | - A clear description of the enhancement. 21 | - Any relevant examples or references. 22 | 23 | ### Pull Requests 24 | 25 | We welcome pull requests! To ensure a smooth process, please follow these guidelines: 26 | 27 | 1. Fork the repository. 28 | 2. Create a new branch for your feature or bugfix. 29 | 3. Write clear and concise commit messages. 30 | 4. Ensure your code follows the project's coding standards. 31 | 5. Write tests for your changes. 32 | 6. Open a pull request and provide a detailed description of your changes. 33 | 34 | ### Coding Standards 35 | 36 | - Follow the [C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions). 37 | - Use meaningful variable and function names. 38 | - Include comments and documentation where necessary. 39 | 40 | ### Tests 41 | 42 | Ensure that you write tests for your contributions. Run all tests to verify your changes do not break existing functionality. 43 | 44 | ### Documentation 45 | 46 | If your changes affect the project's documentation, please update it accordingly. This includes the README, API documentation, and any other relevant files. 47 | 48 | ## Acknowledgements 49 | 50 | We appreciate all contributions and thank you for your help in improving MCPSharp! 51 | 52 | ## Questions 53 | 54 | If you have any questions or need further assistance, please open an issue or contact the maintainers. 55 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [year] [fullname] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MCPSharp.Example.OllamaChatCLI/MCPClientPool.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp; 2 | using Microsoft.Extensions.AI; 3 | using System.Collections; 4 | 5 | class MCPClientPool : ICollection 6 | { 7 | private readonly List clients = []; 8 | 9 | public List GetAllAIFunctions() 10 | { 11 | var functions = new List(); 12 | clients.ForEach(c => functions.AddRange(c.GetFunctionsAsync().Result)); 13 | return functions; 14 | } 15 | 16 | public int Count => clients.Count; 17 | public bool IsReadOnly => false; 18 | public void Add(string name, McpServerConfiguration server, Func, bool> permissionFunction = null) 19 | { 20 | clients.Add(new MCPClient(name, "0.1.0", server.Command, string.Join(' ', server.Args ?? []), server.Env) 21 | { 22 | GetPermission = permissionFunction ?? ((parameters) => true) 23 | }); 24 | } 25 | 26 | public void Add(MCPClient item) => clients.Add(item); 27 | public void Clear() => clients.Clear(); 28 | public bool Contains(MCPClient item) => clients.Contains(item); 29 | public void CopyTo(MCPClient[] array, int arrayIndex) => clients.CopyTo(array, arrayIndex); 30 | public IEnumerator GetEnumerator() => clients.GetEnumerator(); 31 | public bool Remove(MCPClient item) => clients.Remove(item); 32 | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); 33 | } -------------------------------------------------------------------------------- /MCPSharp.Example.OllamaChatCLI/MCPSharp.Example.OllamaChatCLI.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net9.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Always 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /MCPSharp.Example.OllamaChatCLI/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.AI; 2 | using System.Text; 3 | using System.Text.Json; 4 | 5 | JsonSerializerOptions jsonSerializerOptions = new() { PropertyNameCaseInsensitive = true }; 6 | 7 | McpServerConfigurationCollection conf = JsonSerializer.Deserialize(File.ReadAllText("config.json"), 8 | jsonSerializerOptions)!; 9 | 10 | MCPClientPool clients = []; 11 | foreach (var server in conf.McpServers) 12 | { 13 | clients.Add(server.Key, server.Value, 14 | (parameters) => 15 | { //this is an example permission function, you can replace it with your own. just press y when prompted to allow the tool to run 16 | Console.WriteLine("The Assistant wants to run a tool."); 17 | Console.WriteLine($"\tTool: {parameters["tool"]}"); 18 | Console.WriteLine($"\tParameters:"); 19 | Console.WriteLine(Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(parameters["parameters"]))); 20 | Console.WriteLine("Do you want to allow it? (y/N)"); 21 | return Console.ReadKey().Key == ConsoleKey.Y; 22 | }); 23 | } 24 | 25 | var chatOptions = new ChatOptions { 26 | Tools = clients.GetAllAIFunctions(), 27 | ToolMode = ChatToolMode.Auto //let the assistant choose not to use a tool if it doesn't need to 28 | }; 29 | var chatHistory = new List() { new(ChatRole.System, conf.Models["ollama"].SystemPrompt) }; 30 | var chatClient = new OllamaChatClient(conf.Models["ollama"].Endpoint, conf.Models["ollama"].ModelId).AsBuilder().UseFunctionInvocation().Build(); 31 | 32 | while (true) 33 | { 34 | Console.Write("\n\n[User] >> "); 35 | var input = Console.ReadLine(); 36 | if (input == "bye") break; 37 | chatHistory.Add(new ChatMessage(ChatRole.User, input)); 38 | var response = await chatClient.GetResponseAsync(chatHistory, chatOptions); 39 | Console.WriteLine($"\n\n[Assistant] {DateTime.Now.ToShortTimeString()}: {response}"); 40 | chatHistory.Add(response.Message); 41 | } 42 | 43 | class McpServerConfiguration 44 | { 45 | public required string Command { get; set; } 46 | public string[] Args { get; set; } = []; 47 | public Dictionary Env { get; set; } = []; 48 | } 49 | 50 | class McpServerConfigurationCollection 51 | { 52 | public Dictionary McpServers { get; set; } 53 | public Dictionary Models { get; set; } 54 | } 55 | 56 | 57 | class ModelConfiguration 58 | { 59 | public string Endpoint { get; set; } 60 | public string ModelId { get; set; } 61 | public string SystemPrompt { get; set; } 62 | } 63 | 64 | -------------------------------------------------------------------------------- /MCPSharp.Example.OllamaChatCLI/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcpServers": { 3 | "MCPSharp": { 4 | "command": "MCPSharp.Example.exe" 5 | } 6 | }, 7 | "models": { 8 | "ollama": { 9 | "endpoint": "http://localhost:11434/", 10 | "modelId": "llama3.2:latest", 11 | "systemPrompt": "your name is MCPSharp and you are a chill, slightly sarcastic assistant. You have access to many tools, but you should only use them if you feel like you need to - do not feel pressured to use a tool unless it will help you complete your task. the write-to-console and echo tools are off limits." 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /MCPSharp.Example/ComplicatedObject.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MCPSharp.Example 4 | { 5 | /// 6 | /// A complicated object 7 | /// 8 | public class ComplicatedObject() 9 | { 10 | /// The name of the object 11 | [JsonPropertyName("name")] 12 | public string Name { get; set; } = ""; 13 | 14 | /// The age of the object 15 | [JsonPropertyName("age")] 16 | public int Age { get; set; } = 0; 17 | 18 | /// The hobbies of the object 19 | [JsonPropertyName("hobbies")] 20 | public string[] Hobbies { get; set; } = []; 21 | } 22 | } -------------------------------------------------------------------------------- /MCPSharp.Example/MCPDev.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp.Example 2 | { 3 | ///testing interface for custom .net mcp server 4 | public class MCPDev() 5 | { 6 | [McpResource("name", "test://{name}")] 7 | public string Name(string name) => $"hello {name}"; 8 | 9 | 10 | [McpResource("settings", "test://settings", "string", "the settings document")] 11 | public string Settings { get; set; } = "settings"; 12 | 13 | 14 | [McpTool("write-to-console", "write a string to the console")] 15 | public static void WriteToConsole(string message) => Console.WriteLine(message); 16 | 17 | ///just returns a message for testing. 18 | [McpTool] 19 | public static string Hello() => "hello, claude."; 20 | 21 | ///returns ths input string back 22 | ///the string to echo 23 | [McpTool] 24 | public static string Echo([McpParameter(true)] string input) => input; 25 | 26 | ///Add Two Numbers 27 | ///first number 28 | ///second number 29 | [McpTool] 30 | public static string Add(int a, int b) => (a + b).ToString(); 31 | 32 | 33 | /// 34 | /// Adds a complex object 35 | /// 36 | /// 37 | /// 38 | [McpTool] 39 | public static string AddComplex(ComplicatedObject obj) => $"Name: {obj.Name}, Age: {obj.Age}, Hobbies: {string.Join(", ", obj.Hobbies)}"; 40 | 41 | /// 42 | /// throws an exception - for ensuring we handle them gracefully 43 | /// 44 | /// 45 | /// 46 | [McpFunction("throw_exception")] //leaving this one as [McpFunction] for testing purposes 47 | public static string Exception() => throw new Exception("This is an exception"); 48 | } 49 | } -------------------------------------------------------------------------------- /MCPSharp.Example/MCPSharp.Example.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net9.0 6 | enable 7 | enable 8 | AnyCPU;x64 9 | False 10 | 11 | 12 | 13 | true 14 | 15 | 16 | 17 | embedded 18 | 19 | 20 | 21 | embedded 22 | 23 | 24 | 25 | embedded 26 | 27 | 28 | 29 | embedded 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /MCPSharp.Example/Program.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp; 2 | using MCPSharp.Model; 3 | using MCPSharp.ExternalExample; 4 | using MCPSharp.Model.Schemas; 5 | 6 | MCPServer.Register(); 7 | MCPServer.Register(); 8 | 9 | MCPServer.AddToolHandler( new Tool() 10 | { 11 | Name = "dynamicTool", 12 | Description = "A Test Tool", 13 | InputSchema = new InputSchema { 14 | Type = "object", 15 | Required = ["input"], 16 | Properties = new Dictionary{ 17 | {"input", new ParameterSchema{Type="string", Description="the input"}}, 18 | {"input2", new ParameterSchema{Type="string", Description="the input2"}} 19 | } 20 | } 21 | }, (string input, string? input2 = null) => { return $"hello, {input}.\n{input2 ?? "didn't feel like filling in the second value just because it wasn't required? shame. just kidding! thanks for your help!"}"; }); 22 | 23 | await MCPServer.StartAsync("TestServer", "1.0"); -------------------------------------------------------------------------------- /MCPSharp.ExternalExample/ExternalTool.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.SemanticKernel; 2 | using System.ComponentModel; 3 | 4 | namespace MCPSharp.ExternalExample 5 | { 6 | 7 | [McpTool("external_tools", "for testing accessing tool classes loaded from a library")] 8 | public class ExternalTool 9 | { 10 | 11 | [McpFunction("dll-tool", "attempts to use a tool that is loaded from an external assembly dll. should return 'success'")] 12 | public static async Task UseAsync() 13 | { 14 | return await Task.Run(()=>"success"); 15 | } 16 | 17 | } 18 | 19 | public class SemKerExample 20 | { 21 | [KernelFunction("SemanticTest")] 22 | [Description("test semantic kernel integration")] 23 | public static async Task UseAsync() 24 | { 25 | return await Task.Run(() => "success"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /MCPSharp.ExternalExample/MCPSharp.Example.Import.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /MCPSharp.Test/AIFunctionAbstractionTests.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model.Results; 2 | using Microsoft.Extensions.AI; 3 | using System.Text.Json; 4 | using System.Xml.Linq; 5 | 6 | namespace MCPSharp.Test 7 | { 8 | [TestClass] 9 | public class AIFunctionAbstractionTests 10 | { 11 | private static MCPClient client; 12 | private static IList functions; 13 | 14 | [ClassInitialize] 15 | public static async Task ClassInitialize(TestContext context) 16 | { 17 | client = new("Test Client", "1.0.0", "dotnet", "MCPSharp.Example.dll"); 18 | functions = await client.GetFunctionsAsync(); 19 | } 20 | 21 | [TestCategory("AIFunctions")] 22 | [TestMethod("Tools/call no parameters")] 23 | public async Task TestInvokingAnAIFunction() 24 | { 25 | 26 | var function = functions.First(f => f.Name == "Hello"); 27 | CallToolResult result = (CallToolResult)(await function!.InvokeAsync())!; 28 | Assert.IsFalse(result.IsError, $"{result.Content[0].Text}"); 29 | Assert.AreEqual("hello, claude.", result.Content[0].Text); 30 | } 31 | 32 | [TestCategory("AIFunctions")] 33 | [TestMethod("Tools/call with parameters")] 34 | public async Task TestInvokingAnAIFunctionWithParameters() 35 | { 36 | 37 | var function = functions.First(f => f.Name == "Echo"); 38 | var Schema = function.JsonSchema; 39 | Console.WriteLine(Schema); 40 | CallToolResult result = (CallToolResult)(await function.InvokeAsync(new Dictionary { { "input", "hello there" } }))!; 41 | 42 | Assert.IsFalse(result.IsError); 43 | 44 | var content = result.Content[0].Text; 45 | Assert.AreEqual("hello there", content); 46 | 47 | } 48 | 49 | [ClassCleanup] 50 | public static void ClassCleanup() 51 | { 52 | client?.Dispose(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MCPSharp.Test/ClientTests.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace MCPSharp.Test 4 | { 5 | [TestClass] 6 | public class ClientTests 7 | { 8 | public static MCPClient client; 9 | 10 | [ClassInitialize] 11 | public static void ClassInitialize(TestContext context) 12 | { 13 | client = new("Test Client", "1.0.0", 14 | RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c:\\program files\\nodejs\\npx.cmd" : "npx", 15 | "-y @modelcontextprotocol/server-everything") 16 | { GetPermission = (Dictionary parameters) => { return true; } }; 17 | } 18 | 19 | 20 | [ClassCleanup] 21 | public static void ClassCleanup() { client?.Dispose(); } 22 | 23 | [TestCategory("Tools")] 24 | [TestMethod("Client - Tools/list")] 25 | public async Task TestListTools() 26 | { 27 | var tools = await client.GetToolsAsync(); 28 | Assert.IsNotNull(tools); 29 | Assert.IsTrue(tools.Count > 0); 30 | tools.ForEach(tool => 31 | { 32 | Assert.IsFalse(string.IsNullOrEmpty(tool.Name)); 33 | Assert.IsFalse(string.IsNullOrEmpty(tool.Description)); 34 | Console.WriteLine(tool.Name); 35 | }); 36 | } 37 | 38 | [TestCategory("Tools")] 39 | [TestMethod("Client - Tools/Call")] 40 | public async Task TestCallTool() 41 | { 42 | 43 | var result = await client.CallToolAsync("echo", new Dictionary { { "message", "test" } }); 44 | 45 | string response = result.Content[0].Text; 46 | Assert.AreEqual("Echo: test", response); 47 | Assert.AreEqual("text", result.Content[0].Type); 48 | 49 | } 50 | 51 | [TestCategory("Prompts")] 52 | [TestMethod("Client - Prompts/List")] 53 | public async Task TestListPrompts() 54 | { 55 | var result = await client.GetPromptListAsync(); 56 | Assert.IsFalse(result.Prompts.Count != 0); 57 | } 58 | 59 | [TestCategory("Resources")] 60 | [TestMethod("Client - Resources/List")] 61 | public async Task TestResources() 62 | { 63 | var result = await client.GetResourcesAsync(); 64 | Assert.IsTrue(result.Resources.Count != 0); 65 | result.Resources.ForEach(result => 66 | { 67 | Console.WriteLine(result.Name); 68 | }); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /MCPSharp.Test/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "", Scope = "member", Target = "~M:MCPSharp.Test.STDIOTransportTests.Test_ListTools~System.Threading.Tasks.Task")] 9 | [assembly: SuppressMessage("Usage", "MSTEST0034:Use 'ClassCleanupBehavior.EndOfClass' with the '[ClassCleanup]'", Justification = "", Scope = "member", Target = "~M:MCPSharp.Test.STDIOTransportTests.ClassCleanup")] 10 | -------------------------------------------------------------------------------- /MCPSharp.Test/MCPSharp.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | latest 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /MCPSharp.Test/MSTestSettings.cs: -------------------------------------------------------------------------------- 1 | [assembly: Parallelize(Scope = ExecutionScope.MethodLevel)] 2 | -------------------------------------------------------------------------------- /MCPSharp.Test/SSETransportTests.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp.Test 2 | { 3 | [TestClass()] 4 | public sealed class SSETransportTests 5 | { 6 | private static MCPClient? _client; 7 | private static MCPClient? client; 8 | 9 | [ClassInitialize] 10 | [Timeout(5000)] 11 | public static void ClassInitialize(TestContext context) { 12 | // _client = new("Test Client", "1.0.0", "MCPSharp.Example.exe"); //start the exe 13 | // client = new(new Uri("http://localhost:8000/sse"), "test_sse_client", "1"); //connect to the sse server 14 | } 15 | 16 | 17 | // [TestMethod("tools/list")] //unucomment this when SSE works 18 | [Timeout(10000)] 19 | public async Task TestListToolsAsync() 20 | { 21 | Assert.IsTrue(client!.Initialized); 22 | var tools = await client.GetToolsAsync(); 23 | Assert.IsNotNull(tools); 24 | Assert.IsTrue(tools.Count > 0); 25 | tools.ForEach(tool => 26 | { 27 | Assert.IsFalse(string.IsNullOrEmpty(tool.Name)); 28 | Assert.IsFalse(string.IsNullOrEmpty(tool.Description)); 29 | Console.WriteLine(tool.Name); 30 | }); 31 | } 32 | 33 | public class TestTool 34 | { 35 | [McpTool("test", "test function")] 36 | public async Task TestFunctionAsync() => await Task.FromResult("test"); 37 | } 38 | 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /MCPSharp.Test/STDIOTransportTests.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Example; 2 | 3 | namespace MCPSharp.Test 4 | { 5 | [TestClass] 6 | public sealed class STDIOTransportTests 7 | { 8 | private readonly static MCPClient client = new("Test Client", "1.0.0", "dotnet", "MCPSharp.Example.dll"); 9 | 10 | [ClassCleanup] 11 | public static void ClassCleanup() { client?.Dispose(); } 12 | 13 | [TestCategory("Tools")] 14 | [TestMethod("Tools/List")] 15 | public async Task Test_ListTools() 16 | { 17 | var tools = await client.GetToolsAsync(); 18 | Assert.IsNotNull(tools); 19 | Assert.IsTrue(tools.Count > 0); 20 | tools.ForEach(tool => 21 | { 22 | Assert.IsFalse(string.IsNullOrEmpty(tool.Name)); 23 | Assert.IsFalse(string.IsNullOrEmpty(tool.Description)); 24 | 25 | Console.WriteLine(tool.Name); 26 | }); 27 | } 28 | 29 | [TestCategory("Tools")] 30 | [TestMethod("Tools/Call")] 31 | public async Task TestCallTool() 32 | { 33 | var result = await client.CallToolAsync("Hello"); 34 | string response = result.Content[0].Text; 35 | 36 | Assert.AreEqual("hello, claude.", response); 37 | Assert.AreEqual("text", result.Content[0].Type); 38 | } 39 | 40 | [TestCategory("Tools")] 41 | [TestMethod("Tools/Call with a dynamically created tool")] 42 | public async Task TestCallDynamicTool() 43 | { 44 | var result = await client.CallToolAsync("dynamicTool", new Dictionary { { "input", "test string" }, { "input2", "another string" } }); 45 | string response = result.Content[0].Text; 46 | Assert.AreEqual("hello, test string.\nanother string", response); 47 | Assert.AreEqual("text", result.Content[0].Type); 48 | 49 | } 50 | 51 | [TestCategory("Tools")] 52 | [TestMethod("Tools/Call with semantic kernel function")] 53 | public async Task TestCallTool_semantic() 54 | { 55 | var result = await client.CallToolAsync("SemanticTest"); 56 | string response = result.Content[0].Text; 57 | Assert.AreEqual("success", response); 58 | Assert.AreEqual("text", result.Content[0].Type); 59 | 60 | } 61 | 62 | [TestCategory("Tools")] 63 | [TestMethod("Tools/Call with Parameters")] 64 | public async Task TestCallToolWithParameters() 65 | { 66 | var result = await client.CallToolAsync("Echo", new Dictionary { { "input", "this is a test of the echo function" } }); 67 | Assert.IsFalse(result.IsError); 68 | string response = result.Content[0].Text; 69 | Assert.AreEqual("this is a test of the echo function", response); 70 | Assert.AreEqual("text", result.Content[0].Type); 71 | 72 | } 73 | 74 | [TestCategory("Misc")] 75 | [TestMethod("Exception Handling")] 76 | public async Task TestException() 77 | { 78 | var result = await client.CallToolAsync("throw_exception"); 79 | string response = result.Content[0].Text; 80 | Assert.AreEqual("This is an exception", response); 81 | Assert.AreEqual("text", result.Content[0].Type); 82 | 83 | } 84 | 85 | [TestCategory("Tools")] 86 | [TestMethod("Tools/Call with Invalid Tool")] 87 | public async Task TestCallInvalidTool() 88 | { 89 | Assert.IsTrue((await client.CallToolAsync("NotARealTool")).IsError); 90 | } 91 | 92 | [TestCategory("Tools")] 93 | [TestMethod("Tools/Call with Invalid Parameters")] 94 | public async Task TestCallToolWithInvalidParameters() 95 | { 96 | var result = await client.CallToolAsync("Echo", new Dictionary { { "invalid_param", "test" } }); 97 | Assert.IsTrue(result.IsError); 98 | } 99 | 100 | [TestCategory("Tools")] 101 | [TestMethod("Tools/Call with dll tool")] 102 | public async Task TestCallExternalTool() 103 | { 104 | var result = await client.CallToolAsync("dll-tool"); 105 | string response = result.Content[0].Text; 106 | Assert.AreEqual("success", response); 107 | Assert.AreEqual("text", result.Content[0].Type); 108 | 109 | } 110 | 111 | 112 | [TestCategory("Prompts")] 113 | [TestMethod("Prompts/List")] 114 | public async Task TestListPrompts() 115 | { 116 | var result = await client.GetPromptListAsync(); 117 | Assert.IsFalse(result.Prompts.Count != 0); 118 | } 119 | 120 | [TestCategory("Misc")] 121 | [TestMethod("Test Ping")] 122 | public async Task TestPing() 123 | { 124 | await client.SendPingAsync(); 125 | } 126 | 127 | [TestCategory("Resources")] 128 | [TestMethod("Resources/List")] 129 | public async Task TestResources() 130 | { 131 | var result = await client.GetResourcesAsync(); 132 | Assert.IsTrue(result.Resources.Count != 0); 133 | result.Resources.ForEach(result => 134 | { 135 | Console.WriteLine(result.Name); 136 | }); 137 | } 138 | 139 | [TestCategory("Tools")] 140 | [TestMethod("Tools/Call with parameter obj")] 141 | public async Task TestCallToolWithParameterObject() 142 | { 143 | var result = await client.CallToolAsync("AddComplex", new Dictionary { { "obj", new ComplicatedObject { Name = "Claude", Age = 25, Hobbies = ["Programming", "Gaming"] } } }); 144 | string response = result.Content[0].Text; 145 | Assert.AreEqual("Name: Claude, Age: 25, Hobbies: Programming, Gaming", response); 146 | Assert.AreEqual("text", result.Content[0].Type); 147 | 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /MCPSharp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.12.35707.178 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MCPSharp.Example", "MCPSharp.Example\MCPSharp.Example.csproj", "{1A4D1BB7-973C-49AD-9564-F45D5B7703EF}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MCPSharp", "MCPSharp\MCPSharp.csproj", "{7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MCPSharp.Test", "MCPSharp.Test\MCPSharp.Test.csproj", "{EAAC2C18-8A35-4CED-B407-582170A7A0F9}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MCPSharp.Example.Import", "MCPSharp.ExternalExample\MCPSharp.Example.Import.csproj", "{6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MCPSharp.Example.OllamaChatCLI", "MCPSharp.Example.OllamaChatCLI\MCPSharp.Example.OllamaChatCLI.csproj", "{73FD6F85-CCEE-4D80-8E8B-154F94511DD2}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Debug|x64 = Debug|x64 20 | Release|Any CPU = Release|Any CPU 21 | Release|x64 = Release|x64 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Debug|x64.ActiveCfg = Debug|x64 27 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Debug|x64.Build.0 = Debug|x64 28 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Release|x64.ActiveCfg = Release|x64 31 | {1A4D1BB7-973C-49AD-9564-F45D5B7703EF}.Release|x64.Build.0 = Release|x64 32 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Debug|x64.ActiveCfg = Debug|Any CPU 35 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Debug|x64.Build.0 = Debug|Any CPU 36 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Release|x64.ActiveCfg = Release|Any CPU 39 | {7FF8D00E-9DBA-435D-80E4-4F1F7E860CDA}.Release|x64.Build.0 = Release|Any CPU 40 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Debug|x64.ActiveCfg = Debug|Any CPU 43 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Debug|x64.Build.0 = Debug|Any CPU 44 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Release|x64.ActiveCfg = Release|Any CPU 47 | {EAAC2C18-8A35-4CED-B407-582170A7A0F9}.Release|x64.Build.0 = Release|Any CPU 48 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Debug|x64.ActiveCfg = Debug|Any CPU 51 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Debug|x64.Build.0 = Debug|Any CPU 52 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Release|x64.ActiveCfg = Release|Any CPU 55 | {6B4E00C3-6CAF-4493-9A4D-9AE602FA9E00}.Release|x64.Build.0 = Release|Any CPU 56 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Debug|x64.ActiveCfg = Debug|Any CPU 59 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Debug|x64.Build.0 = Debug|Any CPU 60 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Release|x64.ActiveCfg = Release|Any CPU 63 | {73FD6F85-CCEE-4D80-8E8B-154F94511DD2}.Release|x64.Build.0 = Release|Any CPU 64 | EndGlobalSection 65 | GlobalSection(SolutionProperties) = preSolution 66 | HideSolutionNode = FALSE 67 | EndGlobalSection 68 | GlobalSection(ExtensibilityGlobals) = postSolution 69 | SolutionGuid = {D0575A42-F4D4-482C-AFD6-791313007E13} 70 | EndGlobalSection 71 | EndGlobal 72 | -------------------------------------------------------------------------------- /MCPSharp/Attributes/McpFunctionAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp 2 | { 3 | /// 4 | /// Attribute to mark a class as an MCP tool. 5 | /// 6 | /// The name of the tool. If not provided, the class name will be used. 7 | /// A description of the tool. 8 | [AttributeUsage(AttributeTargets.Method)] 9 | [Obsolete("To better align with the standard, [McpFunction] has been replaced with [McpTool]. The class itself no longer requres decoration.")] 10 | public class McpFunctionAttribute(string name = null, string description = null) : Attribute 11 | { 12 | /// 13 | /// The name of the tool. If not provided, the class name will be used. 14 | /// 15 | public string Name { get; set; } = name; 16 | /// 17 | /// A description of the tool. 18 | /// 19 | public string Description { get; set; } = description; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /MCPSharp/Attributes/McpParameterAttribute.cs: -------------------------------------------------------------------------------- 1 | #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 2 | using System.Text.Json.Serialization; 3 | 4 | namespace MCPSharp 5 | { 6 | [AttributeUsage(AttributeTargets.Parameter)] 7 | public class McpParameterAttribute(bool required = false, string description = null) : Attribute 8 | { 9 | [JsonPropertyName("required")] 10 | public bool Required { get; set; } = required; 11 | 12 | [JsonPropertyName("description")] 13 | public string Description { get; set; } = description; 14 | } 15 | } 16 | 17 | #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -------------------------------------------------------------------------------- /MCPSharp/Attributes/McpResourceAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp 2 | { 3 | [AttributeUsage(AttributeTargets.All)] 4 | public class McpResourceAttribute(string name = null, string uri=null, string mimeType = null, string description = null) : Attribute 5 | { 6 | public string Name { get; set; } = name; 7 | public string Description { get; set; } = description; 8 | public string Uri { get; set; } = uri; 9 | public string MimeType { get; set; } = mimeType; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MCPSharp/Attributes/McpToolAttribute.cs: -------------------------------------------------------------------------------- 1 | #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 2 | namespace MCPSharp 3 | { 4 | //[AttributeUsage(AttributeTargets.Class)] 5 | public class McpToolAttribute(string name = null, string description = null) : Attribute 6 | { 7 | public string Name { get; set; } = name; 8 | public string Description { get; set; } = description; 9 | } 10 | } 11 | 12 | #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -------------------------------------------------------------------------------- /MCPSharp/Core/MCPClient.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Core.Transport; 2 | using MCPSharp.Model; 3 | using MCPSharp.Model.Parameters; 4 | using MCPSharp.Model.Results; 5 | using Microsoft.Extensions.AI; 6 | using StreamJsonRpc; 7 | using System.Diagnostics; 8 | 9 | namespace MCPSharp 10 | { 11 | 12 | /// 13 | /// MCPSharp Model Context Protocol Client. 14 | /// 15 | public class MCPClient : IDisposable 16 | { 17 | /// 18 | /// Gets or sets the function that determines whether the client has permission to call a tool with the specified parameters. 19 | /// 20 | public Func , bool> GetPermission = (parameters) => true; 21 | 22 | private readonly string _name; 23 | private readonly string _version; 24 | private readonly Process _process; 25 | private readonly JsonRpc _rpc; 26 | 27 | /// 28 | /// Gets a value indicating whether the client has been initialized. 29 | /// 30 | public bool Initialized { get; private set; } = false; 31 | 32 | /// 33 | /// The tools that have been registered with the client. 34 | /// 35 | public List Tools { get; private set; } 36 | 37 | /// 38 | /// Initializes a new instance of the class. 39 | /// 40 | /// The name of the client. 41 | /// The version of the client. 42 | /// The path to the executable server. 43 | /// Dictionary containing enviroment variables 44 | /// Additional arguments for the server. 45 | public MCPClient(string name, string version, string server, string args = null, IDictionary env =null) 46 | { 47 | 48 | ProcessStartInfo startInfo = new(server, args) 49 | { 50 | UseShellExecute = false, 51 | RedirectStandardInput = true, 52 | RedirectStandardOutput = true, 53 | RedirectStandardError = true, 54 | CreateNoWindow = true, 55 | WindowStyle = ProcessWindowStyle.Hidden 56 | }; 57 | 58 | 59 | foreach (var envvar in env?? new Dictionary()) 60 | { 61 | startInfo.EnvironmentVariables.Add(envvar.Key, envvar.Value); 62 | } 63 | 64 | _name = name; 65 | _version = version; 66 | 67 | _process = new() { StartInfo = startInfo }; 68 | _process.Start(); 69 | 70 | var pipe = new DuplexPipe(_process.StandardOutput.BaseStream, _process.StandardInput.BaseStream); 71 | _rpc = new JsonRpc(new NewLineDelimitedMessageHandler(pipe, new SystemTextJsonFormatter() { 72 | JsonSerializerOptions = new System.Text.Json.JsonSerializerOptions { 73 | PropertyNameCaseInsensitive = true, 74 | PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase 75 | } }), this); 76 | _rpc.StartListening(); 77 | 78 | _ = _rpc.InvokeAsync("initialize", 79 | [ 80 | "2024-11-05", 81 | new { 82 | roots = new { listChanged = false }, 83 | sampling = new { }, 84 | tools = new { listChanged = true } 85 | }, 86 | 87 | new { 88 | name = _name, 89 | version = _version } 90 | ]); 91 | 92 | _ = _rpc.NotifyAsync("notifications/initialized"); 93 | _ = GetToolsAsync(); 94 | } 95 | 96 | /// 97 | /// MCP standard ping function 98 | /// 99 | /// 100 | [JsonRpcMethod("ping")] 101 | public static async Task RecievePingAsync() => await Task.FromResult(new()); 102 | 103 | 104 | /// 105 | /// MCP tools list changed notification 106 | /// 107 | /// 108 | [JsonRpcMethod("notifications/tools/list_changed")] 109 | public async Task ToolsListChangedAsync() => await GetToolsAsync(); 110 | 111 | 112 | 113 | /// 114 | /// Expose tools as Microsoft.Extensions.AI AIFunctions 115 | /// 116 | /// 117 | public async Task> GetFunctionsAsync() 118 | { 119 | List functions = []; 120 | 121 | await GetToolsAsync(); 122 | 123 | foreach (var tool in Tools) 124 | { 125 | MCPFunction function = new(tool, this); 126 | functions.Add(function); 127 | } 128 | 129 | return functions; 130 | } 131 | 132 | 133 | /// 134 | /// Gets a list of tools from the MCP server. 135 | /// 136 | /// A task that represents the asynchronous operation. The task result contains a list of tools. 137 | public async Task> GetToolsAsync() 138 | { 139 | Tools = (await _rpc.InvokeWithParameterObjectAsync("tools/list")).Tools; 140 | return Tools; 141 | } 142 | 143 | /// 144 | /// Calls a tool with the given name and parameters. 145 | /// 146 | /// The name of the tool to call. 147 | /// The parameters to pass to the tool. 148 | /// A task that represents the asynchronous operation. The task result contains the result of the tool call. 149 | public async Task CallToolAsync(string name, Dictionary parameters) 150 | { 151 | if (!GetPermission(new Dictionary { ["tool"] = name, ["parameters"] = parameters })) 152 | return new CallToolResult() { 153 | IsError = true, 154 | Content = [new Model.Content.TextContent() { 155 | Text = "Permission Denied." }] 156 | }; 157 | 158 | return await _rpc.InvokeWithParameterObjectAsync( 159 | "tools/call", new ToolCallParameters { Arguments = parameters, Name = name }); 160 | } 161 | 162 | 163 | /// 164 | /// Calls a tool with the given name. 165 | /// 166 | /// The name of the tool to call. 167 | /// A task that represents the asynchronous operation. The task result contains the result of the tool call. 168 | public async Task CallToolAsync(string name) => await CallToolAsync(name, []); 169 | 170 | /// 171 | /// Gets a list of resources from the MCP server. 172 | /// 173 | /// A task that represents the asynchronous operation. The task result contains a list of resources. 174 | public async Task GetResourcesAsync() => await _rpc.InvokeWithParameterObjectAsync("resources/list"); 175 | 176 | /// 177 | /// Gets a list of resource templates from the MCP server. 178 | /// 179 | /// A task that represents the asynchronous operation. The task result contains a list of resource templates. 180 | public async Task GetResourceTemplatesAsync() => await _rpc.InvokeWithParameterObjectAsync("resources/templates/list"); 181 | 182 | /// 183 | /// Pings the MCP server. 184 | /// 185 | /// A task that represents the asynchronous operation. The task result contains the ping response. 186 | public async Task SendPingAsync() => await _rpc.InvokeWithParameterObjectAsync("ping"); 187 | 188 | /// 189 | /// Gets a list of prompts from the MCP server. 190 | /// 191 | /// A task that represents the asynchronous operation. The task result contains a list of prompts. 192 | public async Task GetPromptListAsync() => await _rpc.InvokeWithParameterObjectAsync("prompts/list"); 193 | 194 | /// 195 | /// Releases all resources used by the class. 196 | /// 197 | public void Dispose() 198 | { 199 | GC.SuppressFinalize(this); 200 | 201 | _ = _rpc.DispatchCompletion; 202 | 203 | _rpc.Dispose(); 204 | 205 | _process.Kill(); 206 | _process.WaitForExit(); 207 | _process.Dispose(); 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /MCPSharp/Core/MCPFunction.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model; 2 | using MCPSharp.Model.Schemas; 3 | using Microsoft.Extensions.AI; 4 | using System.Dynamic; 5 | using System.Text.Json; 6 | using System.Text.Json.Serialization; 7 | 8 | namespace MCPSharp 9 | { 10 | public class MCPFunctionInputSchema : InputSchema 11 | { 12 | public MCPFunctionInputSchema(string name, string description, InputSchema schema) 13 | { 14 | Name = name; 15 | Description = description; 16 | Schema = schema.Schema; 17 | Required = schema.Required; 18 | Properties = schema.Properties; 19 | Type = schema.Type; 20 | AdditionalProperties = schema.AdditionalProperties; 21 | } 22 | 23 | [JsonPropertyName("title")] 24 | public string Name; 25 | 26 | [JsonPropertyName("description")] 27 | public string Description; 28 | } 29 | 30 | public class MCPFunctionSchema 31 | { 32 | [JsonPropertyName("description")] 33 | string Description { get; set; } 34 | 35 | [JsonPropertyName("type")] 36 | string Type { get; set; } 37 | 38 | [JsonPropertyName("properties")] 39 | Dictionary Properties { get; set; } 40 | 41 | } 42 | public class MCPFunction(Tool tool, MCPClient client) : AIFunction() 43 | { 44 | private Tool _tool = tool; 45 | private readonly MCPClient _client = client; 46 | public override string Description => _tool.Description; 47 | public override string Name => _tool.Name; 48 | public override JsonElement JsonSchema => JsonSerializer.SerializeToElement(new MCPFunctionInputSchema(_tool.Name, _tool.Description, _tool.InputSchema)); 49 | 50 | 51 | protected override async Task InvokeCoreAsync(IEnumerable> arguments, CancellationToken cancellationToken) 52 | { 53 | return await _client.CallToolAsync(_tool.Name, arguments.ToDictionary(p => p.Key, p => p.Value)); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /MCPSharp/Core/MCPServer.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Core.Tools; 2 | using MCPSharp.Core.Transport; 3 | using MCPSharp.Model; 4 | using Microsoft.VisualStudio.Threading; 5 | using StreamJsonRpc; 6 | using System.Reflection; 7 | 8 | namespace MCPSharp 9 | { 10 | /// 11 | /// Main class for the MCP server. 12 | /// 13 | public class MCPServer 14 | { 15 | private static readonly MCPServer _instance = new(); 16 | private readonly JsonRpc _rpc; 17 | private readonly Stream StandardOutput; 18 | 19 | private readonly ToolManager _toolManager = new() 20 | { 21 | ToolChangeNotification = () => { if (EnableToolChangeNotification) 22 | _= _instance._rpc.InvokeWithParameterObjectAsync("notifications/tools/list_changed", null);} 23 | }; 24 | 25 | private readonly ResourceManager _resouceManager = new(); 26 | 27 | private readonly ServerRpcTarget _target; 28 | private readonly CancellationTokenSource _cancellationTokenSource = new(); 29 | 30 | /// 31 | /// true if tool change notifications are enabled. This will set to true if the client supports it during initialization, but can be disabled. 32 | /// 33 | public static bool EnableToolChangeNotification { get; set; } = false; 34 | 35 | /// 36 | /// Enables periodic pings to the client. If the client does not respond, the server will exit. Default is true, as clients are supposed to respond to pings. 37 | /// 38 | public static bool EnablePing { get; set; } = true; 39 | 40 | /// 41 | /// The name and version of the server implementation 42 | /// 43 | public Implementation Implementation; 44 | 45 | /// 46 | /// Any calls to Console.Write() will be sent to this text writer. Overwrite it if you wish to capture this stream. 47 | /// 48 | public readonly TextWriter RedirectedOutput = TextWriter.Null; 49 | 50 | /// 51 | /// Constructor for the MCP server. 52 | /// 53 | private MCPServer() 54 | { 55 | Implementation = new(); 56 | _target = new(_toolManager, _resouceManager, Implementation); 57 | Console.SetOut(RedirectedOutput); 58 | _rpc = new JsonRpc(new NewLineDelimitedMessageHandler(new StdioTransportPipe(), 59 | new SystemTextJsonFormatter() { 60 | JsonSerializerOptions = new System.Text.Json.JsonSerializerOptions { 61 | PropertyNameCaseInsensitive = true, 62 | PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase 63 | } }), _target); 64 | 65 | _rpc.StartListening(); 66 | } 67 | 68 | /// 69 | /// Registers a tool with the server. 70 | /// 71 | /// 72 | [Obsolete("Call Register instead. The method has been renamed to clear any confusion. They are functionally identical")] 73 | public static void RegisterTool() where T : class, new() => _instance._toolManager.Register(); 74 | 75 | /// 76 | /// Registers a tool with the server. 77 | /// 78 | /// 79 | public static void Register() where T : class, new()=>_ = _instance.RegisterAsync(); 80 | public async Task RegisterAsync() where T : class, new() { _toolManager.Register(); _resouceManager.Register(); } 81 | public static void AddToolHandler(Tool tool, Delegate func) => _instance._toolManager.AddToolHandler(new ToolHandler(tool, func.Method)); 82 | 83 | /// 84 | /// forward Console.WriteLine() to a TextWriter 85 | /// 86 | /// 87 | public static void SetOutput(TextWriter output) => Console.SetOut(output); 88 | 89 | /// 90 | /// Starts the MCP Server, registers all tools, and starts listening for requests. 91 | /// 92 | /// The name of the server. 93 | /// The version of the server. 94 | /// A task that represents the asynchronous operation. 95 | public static async Task StartAsync(string serverName, string version) 96 | { 97 | _instance.Implementation = new(serverName, version); 98 | 99 | var allTypes = Assembly.GetEntryAssembly()!.GetTypes() 100 | .Where(t => 101 | { 102 | bool classHasToolAttribute = t.GetCustomAttribute() != null; 103 | bool methodHasToolAttribute = t.GetMethods().Any(m => m.GetCustomAttribute() != null); 104 | bool methodHasFunctionAttribute = t.GetMethods().Any(m => m.GetCustomAttribute() != null); 105 | bool methodHasResourceAttribute = t.GetMethods().Any(m => m.GetCustomAttribute() != null); 106 | 107 | return classHasToolAttribute || methodHasToolAttribute || methodHasFunctionAttribute || methodHasResourceAttribute; 108 | }); 109 | 110 | foreach (var toolType in allTypes) 111 | { 112 | var registerMethod = typeof(MCPServer).GetMethod(nameof(ToolManager.Register))?.MakeGenericMethod(toolType); 113 | registerMethod?.Invoke(_instance, null); 114 | } 115 | 116 | await Task.Delay(-1); 117 | } 118 | 119 | private async Task StartPingThreadAsync() 120 | { 121 | while (!_cancellationTokenSource.Token.IsCancellationRequested) 122 | { 123 | await Task.Delay(5000); 124 | if (!EnablePing) break; 125 | 126 | try 127 | { 128 | var response = await _rpc.InvokeWithParameterObjectAsync("ping", null).WithTimeout(TimeSpan.FromMilliseconds(500)); 129 | 130 | if (response == null) 131 | { 132 | _rpc.Dispose(); 133 | Environment.Exit(1); 134 | } 135 | } 136 | 137 | catch (Exception) 138 | { 139 | _rpc.Dispose(); 140 | Environment.Exit(1); 141 | } 142 | } 143 | } 144 | 145 | internal void Dispose() 146 | { 147 | _cancellationTokenSource.Cancel(); 148 | _rpc.Dispose(); 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /MCPSharp/Core/ServerRpcTarget.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Core.Tools; 2 | using MCPSharp.Model; 3 | using MCPSharp.Model.Capabilities; 4 | using MCPSharp.Model.Parameters; 5 | using MCPSharp.Model.Results; 6 | using StreamJsonRpc; 7 | 8 | namespace MCPSharp 9 | { 10 | class ServerRpcTarget(ToolManager toolManager, ResourceManager resourceManager, Implementation implementation) 11 | { 12 | private Implementation _clientInfo; 13 | private ClientCapabilities _clientCapabilities = new(); 14 | 15 | /// 16 | /// Initializes the server with the specified protocol version, client capabilities, and client information. 17 | /// 18 | /// The protocol version. 19 | /// The client capabilities. 20 | /// The client information. 21 | /// The result of the initialization process. 22 | [JsonRpcMethod("initialize")] 23 | public async Task InitializeAsync(string protocolVersion, object capabilities, Implementation clientInfo) 24 | { 25 | 26 | if (capabilities is ClientCapabilities cc) 27 | { 28 | _clientCapabilities = cc; 29 | } 30 | 31 | _clientInfo = clientInfo ?? new(); 32 | 33 | if (_clientCapabilities.Tools.TryGetValue("listChanged", out object value)) 34 | { 35 | if (value is bool boolValue) 36 | MCPServer.EnableToolChangeNotification = boolValue; 37 | } 38 | 39 | return await Task.FromResult( 40 | new(protocolVersion, new ServerCapabilities { 41 | Tools = new() { { "listChanged", true } } 42 | }, implementation)); 43 | } 44 | 45 | /// 46 | /// Handles the "notifications/initialized" JSON-RPC method. 47 | /// 48 | /// A task that represents the asynchronous operation. 49 | [JsonRpcMethod("notifications/initialized")] 50 | public static async Task InitializedAsync() => await Task.Run(() => { }); 51 | 52 | /// 53 | /// Lists the resources available on the server. 54 | /// 55 | /// A task that represents the asynchronous operation. The task result contains the list of resources. 56 | [JsonRpcMethod("resources/list")] 57 | public async Task ListResourcesAsync() => await Task.Run(() => new ResourcesListResult() { Resources = resourceManager.Resources }); 58 | 59 | /// 60 | /// Lists the resource templates available on the server. 61 | /// 62 | /// A task that represents the asynchronous operation. The task result contains the list of resource templates. 63 | [JsonRpcMethod("resources/templates/list")] 64 | public static async Task ListResourceTemplatesAsync() => await Task.Run(() => new ResourceTemplateListResult()); 65 | 66 | /// 67 | /// Calls a tool with the specified parameters. 68 | /// 69 | /// The parameters for the tool call. 70 | /// A task that represents the asynchronous operation. The task result contains the result of the tool call. 71 | [JsonRpcMethod("tools/call", UseSingleObjectParameterDeserialization = true)] 72 | public async Task CallToolAsync(ToolCallParameters parameters) => 73 | !toolManager.Tools.TryGetValue(parameters.Name, out var toolHandler) 74 | ? new CallToolResult { IsError = true, Content = [new Model.Content.TextContent { Text = $"Tool {parameters.Name} not found" }] } 75 | : await toolHandler.HandleAsync(parameters.Arguments); 76 | 77 | /// 78 | /// Lists the tools available on the server. 79 | /// 80 | /// A task that represents the asynchronous operation. The task result contains the list of tools. 81 | [JsonRpcMethod("tools/list")] 82 | public async Task ListToolsAsync(object parameters = null) 83 | { 84 | _ = parameters; 85 | return await Task.FromResult(new ToolsListResult([.. toolManager.Tools.Values.Select(t => t.Tool)])); 86 | } 87 | 88 | /// 89 | /// Pings the server. 90 | /// 91 | /// A task that represents the asynchronous operation. The task result contains the ping response. 92 | [JsonRpcMethod("ping")] 93 | public static async Task PingAsync() => await Task.FromResult(new()); 94 | 95 | /// 96 | /// Lists the prompts available on the server. 97 | /// 98 | /// A task that represents the asynchronous operation. The task result contains the list of prompts. 99 | [JsonRpcMethod("prompts/list")] 100 | public static async Task ListPromptsAsync() => await Task.Run(() => new PromptListResult()); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /MCPSharp/Core/Tools/ToolHandler.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model; 2 | using MCPSharp.Model.Content; 3 | using MCPSharp.Model.Results; 4 | using System.Reflection; 5 | using System.Text.Json; 6 | 7 | namespace MCPSharp.Core.Tools 8 | { 9 | public class ToolHandler(Tool tool, MethodInfo method) 10 | { 11 | public Tool Tool = tool; 12 | private readonly MethodInfo _method = method; 13 | 14 | public async Task HandleAsync(Dictionary parameters, CancellationToken cancellationToken = default) 15 | { 16 | try 17 | { 18 | 19 | var inputValues = new Dictionary(); 20 | foreach (var par in _method.GetParameters()) 21 | { 22 | if (parameters.TryGetValue(par.Name, out var value)) { 23 | if (value is JsonElement element) 24 | { 25 | value = JsonSerializer.Deserialize(element.GetRawText(), par.ParameterType); 26 | } 27 | 28 | inputValues.Add(par.Name, value); 29 | } 30 | else 31 | { 32 | inputValues.Add(par.Name, par.ParameterType.IsValueType ? Activator.CreateInstance(par.ParameterType) : null); 33 | } 34 | } 35 | 36 | if (cancellationToken.IsCancellationRequested) 37 | { 38 | return new CallToolResult { IsError = true, Content = [new TextContent("Operation was cancelled")] }; 39 | } 40 | 41 | var result = _method.Invoke(Activator.CreateInstance(_method.DeclaringType),[.. inputValues.Values]); 42 | 43 | 44 | if (cancellationToken.IsCancellationRequested) 45 | { 46 | return new CallToolResult { IsError = true, Content = [new TextContent("Operation was cancelled")] }; 47 | } 48 | 49 | if (result is Task task) 50 | { 51 | await task.ConfigureAwait(false); 52 | var resultProperty = task.GetType().GetProperty("Result"); 53 | result = resultProperty?.GetValue(task); 54 | } 55 | 56 | if (result is string resultString) 57 | return new CallToolResult { Content = [new (resultString)]}; 58 | 59 | if (result is string[] resultStringArray) 60 | return new CallToolResult { Content = [.. resultStringArray.Select(s => new TextContent(s))] }; 61 | 62 | if (result is null) 63 | { 64 | return new CallToolResult { IsError = true, Content = [new("null")] }; 65 | } 66 | 67 | if (result is JsonElement jsonElement) 68 | { 69 | return new CallToolResult { Content = [new(jsonElement.GetRawText())] }; 70 | } 71 | 72 | else return new CallToolResult { Content = [new(result.ToString())] }; 73 | } 74 | catch (Exception ex) 75 | { 76 | var e = ex is TargetInvocationException tie ? tie.InnerException ?? tie : ex; 77 | var stackTrace = e.StackTrace?.Split([Environment.NewLine], StringSplitOptions.None) 78 | .Where(line => !line.Contains("System.RuntimeMethodHandle.InvokeMethod") 79 | && !line.Contains("System.Reflection.MethodBaseInvoker.InvokeWithNoArgs")).ToArray(); 80 | 81 | return new CallToolResult 82 | { 83 | IsError = true, 84 | Content = 85 | [ 86 | new TextContent { Text = $"{e.Message}" }, 87 | new TextContent { Text = $"StackTrace:\n{string.Join("\n", stackTrace)}" } 88 | ] 89 | }; 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /MCPSharp/Core/Tools/ToolManager.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model.Schemas; 2 | using MCPSharp.Model; 3 | using Microsoft.SemanticKernel; 4 | using System.ComponentModel.DataAnnotations; 5 | using System.ComponentModel; 6 | using System.Reflection; 7 | using System.Resources; 8 | using Microsoft.Extensions.AI; 9 | using System.Reflection.Metadata; 10 | 11 | namespace MCPSharp.Core.Tools 12 | { 13 | class ResourceManager 14 | { 15 | public readonly List Resources = []; 16 | public void Register() where T : class, new() 17 | { 18 | var type = typeof(T); 19 | 20 | foreach (var method in type.GetMethods()) 21 | { 22 | var resAttr = method.GetCustomAttribute(); 23 | if (resAttr != null) 24 | { 25 | Resources.Add(new Resource() 26 | { 27 | Name = resAttr.Name, 28 | Description = resAttr.Description, 29 | Uri = resAttr.Uri, 30 | MimeType = resAttr.MimeType 31 | }); 32 | } 33 | } 34 | 35 | foreach (var property in type.GetProperties()) 36 | { 37 | 38 | var resAttr = property.GetCustomAttribute(); 39 | if (resAttr != null) 40 | { 41 | Resources.Add(new Resource() 42 | { 43 | Name = resAttr.Name, 44 | Description = resAttr.Description, 45 | Uri = resAttr.Uri, 46 | MimeType = resAttr.MimeType 47 | }); 48 | } 49 | } 50 | } 51 | } 52 | class ToolManager 53 | { 54 | 55 | public readonly Dictionary Tools = []; 56 | 57 | //triggertoolchahge notification when a tool is added 58 | public Action ToolChangeNotification = () => { }; 59 | 60 | /// 61 | /// Scans a class for Tools and resources and registers them with the server 62 | /// 63 | public void Register() where T : class, new() 64 | { 65 | 66 | var type = typeof(T); 67 | 68 | foreach (var method in type.GetMethods()) 69 | { 70 | RegisterMcpFunction(method); 71 | RegisterSemanticKernelFunction(method); 72 | } 73 | 74 | ToolChangeNotification.Invoke(); 75 | } 76 | 77 | public void AddToolHandler(ToolHandler tool) 78 | { 79 | Tools[tool.Tool.Name] = tool; 80 | ToolChangeNotification.Invoke(); 81 | } 82 | 83 | private void RegisterSemanticKernelFunction(MethodInfo method) 84 | { 85 | var kernelFunctionAttribute = method.GetCustomAttribute(); 86 | if (kernelFunctionAttribute == null) return; 87 | 88 | var parameters = method.GetParameters(); 89 | 90 | Dictionary parameterSchemas = []; 91 | 92 | foreach (var parameter in parameters) 93 | { 94 | parameterSchemas.Add(parameter.Name, GetParameterSchema(parameter)); 95 | } 96 | 97 | 98 | Tools[kernelFunctionAttribute.Name] = new ToolHandler(new Tool 99 | { 100 | Name = kernelFunctionAttribute.Name, 101 | Description = method.GetCustomAttribute().Description ?? "", 102 | InputSchema = new InputSchema 103 | { 104 | Properties = parameterSchemas, 105 | Required = parameterSchemas.Where(kvp => kvp.Value.Required).Select(kvp => kvp.Key).ToList(), 106 | } 107 | }, method!); 108 | } 109 | 110 | private ParameterSchema GetParameterSchema(ParameterInfo parameter) 111 | { 112 | string type = parameter.ParameterType switch 113 | { 114 | Type t when t == typeof(string) => "string", 115 | Type t when t == typeof(int) || t == typeof(double) || t == typeof(float) => "number", 116 | Type t when t == typeof(bool) => "boolean", 117 | Type t when t.IsArray => "array", 118 | Type t when t == typeof(DateTime) => "string", 119 | _ => "object" 120 | }; 121 | 122 | var schema = new ParameterSchema 123 | { 124 | Type = type, 125 | Description = parameter.GetXmlDocumentation() ?? parameter.GetCustomAttribute()?.Description ?? "", 126 | Required = parameter.GetCustomAttribute() != null, 127 | Contents = type == "object" ? AIJsonUtilities.CreateJsonSchema(parameter.ParameterType) : null 128 | } ; 129 | 130 | return schema; 131 | } 132 | 133 | private void RegisterMcpFunction(MethodInfo method) 134 | { 135 | string name = ""; 136 | string description = ""; 137 | 138 | var mcpFuncAttr = method.GetCustomAttribute(); 139 | if (mcpFuncAttr != null) 140 | { 141 | name = mcpFuncAttr.Name ?? method.Name; 142 | description = mcpFuncAttr.Description ?? method.GetXmlDocumentation(); 143 | } 144 | else 145 | { 146 | var methodAttr = method.GetCustomAttribute(); 147 | if (methodAttr != null) 148 | { 149 | name = methodAttr.Name ?? method.Name; 150 | description = methodAttr.Description ?? method.GetXmlDocumentation(); 151 | } 152 | else { return; } 153 | } 154 | 155 | Dictionary parameterSchemas = []; 156 | 157 | foreach (var parameter in method.GetParameters()) 158 | { 159 | parameterSchemas.Add(parameter.Name, GetParameterSchema(parameter)); 160 | } 161 | 162 | Tools[name] = new ToolHandler(new Tool 163 | { 164 | Name = name, 165 | Description = description ?? "", 166 | InputSchema = new InputSchema 167 | { 168 | Properties = parameterSchemas, 169 | Required = parameterSchemas.Where(kvp => kvp.Value.Required).Select(kvp => kvp.Key).ToList(), 170 | } 171 | }, method!); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /MCPSharp/Core/Transport/DuplexPipe.cs: -------------------------------------------------------------------------------- 1 | using System.IO.Pipelines; 2 | using System.Net.Http; 3 | using System.Net; 4 | using MCPSharp.Core.Transport.SSE; 5 | 6 | namespace MCPSharp.Core.Transport 7 | { 8 | internal class DuplexPipe(Stream reader, Stream writer) : IDuplexPipe 9 | { 10 | private readonly PipeReader _reader = PipeReader.Create(reader); 11 | private readonly PipeWriter _writer = PipeWriter.Create(writer); 12 | 13 | public PipeReader Input => _reader; 14 | public PipeWriter Output => _writer; 15 | } 16 | 17 | internal class StdioTransportPipe : IDuplexPipe 18 | { 19 | private readonly PipeReader _reader = PipeReader.Create(Console.OpenStandardInput()); 20 | private readonly PipeWriter _writer = PipeWriter.Create(Console.OpenStandardOutput()); 21 | 22 | public PipeReader Input => _reader; 23 | public PipeWriter Output => _writer; 24 | } 25 | 26 | internal class SSETransportPipe : IDuplexPipe 27 | { 28 | private readonly HttpClient _httpClient = new(); 29 | private readonly Uri _address; 30 | public SSETransportPipe(Uri address) 31 | { 32 | _address = address; 33 | _reader = PipeReader.Create( _httpClient.GetStreamAsync(_address).Result); 34 | _writer = PipeWriter.Create(new HttpPostStream(_address.ToString())); 35 | } 36 | 37 | private PipeReader _reader; 38 | private PipeWriter _writer; 39 | public PipeReader Input => _reader; 40 | public PipeWriter Output => _writer; 41 | } 42 | } -------------------------------------------------------------------------------- /MCPSharp/Core/Transport/SSE/HttpPostStream.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp.Core.Transport.SSE 2 | { 3 | /// 4 | /// A stream that sends data to an HTTP endpoint using POST requests. 5 | /// 6 | public class HttpPostStream : Stream 7 | { 8 | private readonly string _endpoint; 9 | private readonly MemoryStream _buffer; 10 | private readonly HttpClient _client; 11 | 12 | /// 13 | /// Initializes a new instance of the class. 14 | /// 15 | /// 16 | public HttpPostStream(string endpoint) 17 | { 18 | _endpoint = endpoint; 19 | _buffer = new MemoryStream(); 20 | _client = new HttpClient(); 21 | } 22 | 23 | /// 24 | /// Gets a value indicating whether the stream supports reading. 25 | /// 26 | public override bool CanRead => false; 27 | 28 | /// 29 | /// Gets a value indicating whether the stream supports seeking. 30 | /// 31 | public override bool CanSeek => false; 32 | 33 | /// 34 | /// Gets a value indicating whether the stream supports writing. 35 | /// 36 | public override bool CanWrite => true; 37 | 38 | /// 39 | /// Gets the length of the stream. 40 | /// 41 | public override long Length => throw new NotSupportedException(); 42 | 43 | /// 44 | /// Gets or sets the position within the current stream. 45 | /// 46 | public override long Position 47 | { 48 | get => throw new NotSupportedException(); 49 | set => throw new NotSupportedException(); 50 | } 51 | 52 | /// 53 | /// Writes data to the stream. 54 | /// 55 | /// 56 | /// 57 | /// 58 | public override void Write(byte[] buffer, int offset, int count) 59 | { 60 | _buffer.Write(buffer, offset, count); 61 | if (buffer.Contains((byte)'\n')) 62 | { 63 | // Make sure to await the flush 64 | _ = FlushAsync(); 65 | } 66 | } 67 | 68 | /// 69 | /// Flushes the buffer to the endpoint. 70 | /// 71 | /// 72 | /// 73 | public override async Task FlushAsync(CancellationToken cancellationToken) 74 | { 75 | if (_buffer.Length > 0) 76 | { 77 | _buffer.Position = 0; 78 | var content = await new StreamReader(_buffer).ReadToEndAsync(); 79 | _buffer.SetLength(0); 80 | 81 | using var request = new HttpRequestMessage(HttpMethod.Post, _endpoint) 82 | { 83 | Content = new StringContent(content) 84 | }; 85 | using var response = await _client.SendAsync(request, cancellationToken); 86 | //response.EnsureSuccessStatusCode(); 87 | } 88 | } 89 | 90 | /// 91 | /// Flushes the buffer to the endpoint. 92 | /// 93 | public override void Flush() => _ = FlushAsync(); 94 | 95 | /// 96 | /// Reads data from the stream. 97 | /// 98 | /// 99 | /// 100 | /// 101 | /// 102 | /// 103 | public override int Read(byte[] buffer, int offset, int count) => 104 | throw new NotSupportedException(); 105 | 106 | /// 107 | /// Sets the position within the current stream. 108 | /// 109 | /// 110 | /// 111 | /// 112 | /// 113 | public override long Seek(long offset, SeekOrigin origin) => 114 | throw new NotSupportedException(); 115 | 116 | /// 117 | /// Sets the length of the stream. 118 | /// 119 | /// 120 | /// 121 | public override void SetLength(long value) => 122 | throw new NotSupportedException(); 123 | 124 | /// 125 | /// Releases the unmanaged resources used by the and optionally releases the managed resources. 126 | /// 127 | /// 128 | protected override void Dispose(bool disposing) 129 | { 130 | if (disposing) 131 | { 132 | _buffer.Dispose(); 133 | _client.Dispose(); 134 | } 135 | base.Dispose(disposing); 136 | } 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /MCPSharp/Core/Transport/SSE/ServerSentEventsService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | 3 | namespace MCPSharp.Core.Transport.SSE 4 | { 5 | 6 | public class ServerSentEventsService 7 | { 8 | private readonly List<(SseClient Client, MCPServer Instance)> _clients = []; 9 | private readonly object _lock = new(); 10 | private readonly Func _instanceFactory; 11 | 12 | public ServerSentEventsService(Func instanceFactory) 13 | { 14 | _instanceFactory = instanceFactory; 15 | } 16 | 17 | public async Task AddClientAsync(HttpContext context, Stream input) 18 | { 19 | var client = new SseClient(context, input); 20 | var instance = _instanceFactory(input, context.Response.Body); 21 | 22 | lock (_lock) 23 | { 24 | _clients.Add((client, instance)); 25 | } 26 | } 27 | 28 | public async Task RemoveClientAsync(SseClient client) 29 | { 30 | lock (_lock) 31 | { 32 | var index = _clients.FindIndex(x => x.Client == client); 33 | if (index >= 0) 34 | { 35 | _clients[index].Instance.Dispose(); 36 | _clients.RemoveAt(index); 37 | } 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /MCPSharp/Core/Transport/SSE/SseClient.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using System.IO.Pipelines; 3 | 4 | namespace MCPSharp.Core.Transport.SSE 5 | { 6 | public class SseClient 7 | { 8 | private readonly HttpContext _context; 9 | private readonly CancellationTokenSource _disconnectTokenSource; 10 | public Stream Stream; 11 | public SseClient(HttpContext context, Stream stream) 12 | { 13 | _context = context; 14 | _disconnectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); 15 | Stream = stream; 16 | } 17 | 18 | public async Task SendEventAsync(string eventType, string data) 19 | { 20 | try 21 | { 22 | var response = _context.Response; 23 | await response.WriteAsync($"event: {eventType}\n"); 24 | await response.WriteAsync($"data: {data}\n\n"); 25 | await response.Body.FlushAsync(); 26 | } 27 | catch 28 | { 29 | _disconnectTokenSource.Cancel(); 30 | } 31 | } 32 | 33 | public Task WaitForDisconnectAsync() 34 | { 35 | return Task.Delay(Timeout.Infinite, _disconnectTokenSource.Token); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /MCPSharp/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("Style", "IDE0130:Namespace does not match folder structure", Justification = "", Scope = "namespace", Target = "~N:MCPSharp")] 9 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MCPSharp.Core.ToolHandler`1.HandleAsync(System.Collections.Generic.Dictionary{System.String,System.Object},System.Threading.CancellationToken)~System.Threading.Tasks.Task{MCPSharp.Model.Results.CallToolResult}")] 10 | 11 | // the equivalent of #pragma warning disable CS1591 12 | [assembly: SuppressMessage("Style", "CS1591:Missing XML comment for publicly visible type or member", Justification = "", Scope = "namespace", Target = "~N:MCPSharp")] 13 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MCPSharp.MCPServer.Initialize(System.String,MCPSharp.Model.Capabilities.ClientCapabilities,MCPSharp.Model.Implementation)~MCPSharp.Model.Results.InitializeResult")] 14 | -------------------------------------------------------------------------------- /MCPSharp/MCPSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0;net8.0;net9.0 5 | 13.0 6 | enable 7 | disable 8 | 9 | 10 | MCPSharp 11 | 0.9.13 12 | Allen Frise 13 | 14 | MCPSharp - Model Context Protocol for .NET 15 | Build Model Context Protocol (MCP) servers and clients in .NET with MCPSharp. 16 | 17 | Create MCP-compliant tools and functions that AI models can discover and use. 18 | Features easy to use attribute-based API allowing anyone to spin up a server in minutes, 19 | and a Microsoft.Extensions.AI compatible client that generates AIFunctions, 20 | ready to be consumed by any IChatClient or compatible system. 21 | 22 | 23 | await MCPServer.StartAsync("EchoServer", "1.0.0"); 24 | 25 | --- server: 26 | class MyTool 27 | { 28 | [McpTool("echo","returns the input string back to you")] 29 | public string echo(string input) => input; 30 | } 31 | 32 | ---client: 33 | var client = new MCPClient("MyClient","1.0.0", "EchoServer.exe" //or dotnet EchoServer.dll if you wish 34 | await client.CallToolAsync("echo", new Dictionary<string, object>{{"input", "input string to echo"}}); 35 | icon.png 36 | 37 | mcp;sharp;mcpsharp;mcp-sharp;mcp#;ai;machine-learning;json-rpc;api;tools;claude;anthropic;model-context-protocol;tool-calling;model;context;protocol;server;mcp-server;modelcontextprotocol;mcpserver;standard; 38 | 39 | https://github.com/afrise/MCPSharp 40 | git 41 | README.md 42 | true 43 | https://github.com/afrise/MCPSharp 44 | true 45 | * Microsoft.Extensions.AI Integration: MCPSharp now integrates with Microsoft.Extensions.AI, allowing tools to be exposed as AIFunctions 46 | * Semantic Kernel Support: Add tools using Semantic Kernel's KernelFunctionAttribute 47 | * Dynamic Tool Registration: Register tools on-the-fly with custom implementation logic 48 | * Tool Change Notifications: Server now notifies clients when tools are added, updated, or removed 49 | * Complex Object Parameter Support: Better handling of complex objects in tool parameters 50 | * Better Error Handling: Improved error handling with detailed stack traces 51 | 0.9.13 52 | 0.9.13 53 | MIT 54 | latest 55 | 56 | 57 | 58 | 8 59 | 60 | 61 | 62 | 8 63 | 64 | 65 | 66 | 8 67 | 68 | 69 | 70 | 8 71 | 72 | 73 | 74 | 75 | True 76 | \ 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | all 87 | runtime; build; native; contentfiles; analyzers; buildtransitive 88 | 89 | 90 | 91 | 92 | 93 | 94 | Always 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /MCPSharp/Model/Capabilities/ClientCapabilities.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp.Model.Capabilities 2 | { 3 | /// 4 | /// Represents the capabilities of a client. 5 | /// 6 | public class ClientCapabilities 7 | { 8 | /// 9 | /// Gets or sets a value indicating wether roots are supported. 10 | /// 11 | public Dictionary Roots { get; set; } = []; 12 | 13 | /// 14 | /// Gets or sets a value indicating whether sampling is supported. 15 | /// 16 | 17 | public Dictionary Sampling { get; set; } = []; 18 | 19 | /// 20 | /// Gets or sets a value indicating whether tools are supported. 21 | /// 22 | public Dictionary Tools { get; set; } = []; 23 | 24 | /// 25 | /// Gets or sets a value indicating whether resources are supported. 26 | /// 27 | public Dictionary Resources { get; set; } = []; 28 | 29 | /// 30 | /// Gets or sets a value indicating whether prompts are supported. 31 | /// 32 | public Dictionary Prompts { get; set; } = []; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /MCPSharp/Model/Capabilities/ServerCapabilities.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace MCPSharp.Model.Capabilities 3 | { 4 | /// 5 | /// A collection of dictionaries that represent the capabilities of the server. This is sent to the client when negotiating capabilities. 6 | /// 7 | public class ServerCapabilities 8 | { 9 | /// 10 | /// A dictionary of tool capabilities that the server supports. 11 | /// 12 | public Dictionary Tools { get; set; } = []; 13 | 14 | /// 15 | /// A dictionary of resource capabilities that the server supports. 16 | /// 17 | public Dictionary Resources { get; set; } = []; 18 | 19 | /// 20 | /// A dictionary of prompt capabilities that the server supports. 21 | /// 22 | public Dictionary Prompts { get; set; } = []; 23 | 24 | /// 25 | /// A dictionary of sampling capabilities that the server supports. 26 | /// 27 | public Dictionary Sampling { get; set; } = []; 28 | 29 | /// 30 | /// A dictionary of root capabilities that the server supports. 31 | /// 32 | public Dictionary Roots { get; set; } = []; 33 | } 34 | } -------------------------------------------------------------------------------- /MCPSharp/Model/Content/TextContent.cs: -------------------------------------------------------------------------------- 1 | namespace MCPSharp.Model.Content 2 | { 3 | /// 4 | /// This is the basic text object for a message 5 | /// 6 | public class TextContent(string text = null) 7 | { 8 | /// 9 | /// The text of the message 10 | /// 11 | public string Text { get; set; } = text; 12 | /// 13 | /// The type of the content. This is always "text" 14 | /// 15 | public string Type { get; } = "text"; 16 | 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /MCPSharp/Model/Implementation.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MCPSharp.Model 4 | { 5 | /// 6 | /// Represents the implementation details of the MCPSharp server. 7 | /// 8 | public class Implementation 9 | { 10 | /// 11 | /// constructor for the implementation class 12 | /// 13 | public Implementation() 14 | { 15 | } 16 | 17 | /// 18 | /// constructor for the implementation class 19 | /// 20 | /// 21 | /// 22 | public Implementation(string name, string version) : this() 23 | { 24 | Name = name; 25 | Version = version; 26 | } 27 | 28 | /// 29 | /// Gets or sets the name of the implementation. 30 | /// 31 | [JsonPropertyName("name")] 32 | public string Name { get; set; } = "MCPSharp Server"; 33 | 34 | /// 35 | /// Gets or sets the version of the implementation. 36 | /// 37 | [JsonPropertyName("version")] 38 | public string Version { get; set; } = "0.0.1"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /MCPSharp/Model/MetaData.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MCPSharp.Model 4 | { 5 | /// 6 | /// Represents metadata information. 7 | /// 8 | public class MetaData 9 | { 10 | /// 11 | /// Gets or sets the progress token. 12 | /// 13 | [JsonPropertyName("progressToken")] 14 | public int ProgressToken { get; set; } = 0; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /MCPSharp/Model/Parameters/InitializationParameters.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model.Capabilities; 2 | 3 | namespace MCPSharp.Model.Parameters 4 | { 5 | internal class InitializationParameters 6 | { 7 | public required string Version { get; set; } 8 | public required string ProtocolVersion { get; set; } 9 | public required ClientCapabilities Capabilities { get; set; } 10 | public required Implementation ClientInfo { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /MCPSharp/Model/Parameters/ToolCallParameters.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MCPSharp.Model.Parameters 4 | { 5 | /// 6 | /// Represents the parameters for a tool call. 7 | /// 8 | public class ToolCallParameters 9 | { 10 | /// 11 | /// The name of the tool being called 12 | /// 13 | public string Name { get; set; } = ""; 14 | 15 | /// 16 | /// the arguments supplied to the tool 17 | /// 18 | public Dictionary Arguments { get; set; } = []; 19 | 20 | /// 21 | /// metadata 22 | /// 23 | [JsonPropertyName("_meta")] 24 | public MetaData Meta { get; set; } = new(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /MCPSharp/Model/Results/CallToolResult.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model.Content; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace MCPSharp.Model.Results 5 | { 6 | /// 7 | /// Represents the result of a call tool operation. 8 | /// 9 | public class CallToolResult 10 | { 11 | /// 12 | /// Gets or sets a value indicating whether the result is an error. 13 | /// 14 | [JsonPropertyName("isError")] 15 | public bool IsError { get; set; } 16 | 17 | /// 18 | /// Gets or sets the content of the result. 19 | /// 20 | [JsonPropertyName("content")] 21 | public TextContent[] Content { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /MCPSharp/Model/Results/InitializeResult.cs: -------------------------------------------------------------------------------- 1 | using MCPSharp.Model.Capabilities; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace MCPSharp.Model.Results 5 | { 6 | /// 7 | /// Represents the result of an initialization process. 8 | /// 9 | public class InitializeResult(string protocolVersion, ServerCapabilities capabilities, Implementation serverInfo) 10 | { 11 | /// 12 | /// Gets or sets the protocol version. 13 | /// 14 | [JsonPropertyName("protocolVersion")] 15 | public string ProtocolVersion { get; set; } = protocolVersion; 16 | 17 | /// 18 | /// Gets or sets the server capabilities. 19 | /// 20 | [JsonPropertyName("capabilities")] 21 | public ServerCapabilities Capabilities { get; set; } = capabilities; 22 | 23 | /// 24 | /// Gets or sets the server information. 25 | /// 26 | [JsonPropertyName("serverInfo")] 27 | public Implementation ServerInfo { get; set; } = serverInfo; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /MCPSharp/Model/Results/ListToolsResult.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MCPSharp.Model.Results 4 | { 5 | /// 6 | /// Represents the result of listing tools. 7 | /// 8 | public class ListToolsResult 9 | { 10 | /// 11 | /// Gets or sets the list of tools. 12 | /// 13 | [JsonPropertyName("tools")] 14 | public List Tools { get; set; } 15 | 16 | /// 17 | /// Gets or sets the metadata associated with the tools. 18 | /// 19 | [JsonPropertyName("_meta")] 20 | public Dictionary Meta { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /MCPSharp/Model/Results/PromptListResult.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace MCPSharp.Model.Results 4 | { 5 | /// 6 | /// the prompt list result 7 | /// 8 | public class PromptListResult 9 | { 10 | /// 11 | /// the prompts 12 | /// 13 | [JsonProperty("prompts")] 14 | public List Prompts = []; 15 | } 16 | } -------------------------------------------------------------------------------- /MCPSharp/Model/Results/ResourcesListResult.cs: -------------------------------------------------------------------------------- 1 | #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 2 | 3 | using System.Text.Json.Serialization; 4 | 5 | namespace MCPSharp 6 | { 7 | public class ResourcesListResult 8 | { 9 | [JsonPropertyName("resources")] 10 | public List Resources { get; set; } = []; 11 | } 12 | 13 | public class Resource 14 | { 15 | [JsonPropertyName("name")] 16 | public string Name { get; set; } 17 | [JsonPropertyName("uri")] 18 | public string Uri { get; set; } 19 | [JsonPropertyName("description")] 20 | public string Description { get; set; } 21 | [JsonPropertyName("mimeType")] 22 | public string MimeType { get; set; } 23 | } 24 | 25 | public class ResourceTemplateListResult 26 | { 27 | [JsonPropertyName("resourceTemplates")] 28 | public List