How to Use Claude via NuGet | Official Anthropic SDK for C#

When you want to integrate Claude into a C# / .NET project, the first place to look is NuGet. Anthropic distributes an official C# SDK under the name Anthropic, and you can install it with a single dotnet add package Anthropic command. This article focuses specifically on the NuGet path, covering the install command, minimal code, API key configuration, IChatClient integration, and the important caveat that "versions 3.X and below were actually a completely different package."

AI-powered article summarypowered by Claude
結論powered by Claude

The official SDK for calling Claude from C# / .NET is the NuGet package Anthropic, installed with dotnet add package Anthropic. It runs on .NET Standard 2.0 and later and is currently in beta (version 10 and above is the official release).

The biggest pitfall is that versions 3.X and below are a completely different package. Those older versions were built by the tryAGI community and have since been migrated to tryAGI.Anthropic. If you need to keep using the old client, update your reference to that package instead.

The minimal code creates a client with AnthropicClient client = new(); and simply passes a message to client.Messages.Create(). The API key is automatically retrieved from the ANTHROPIC_API_KEY environment variable, and the SDK can also integrate with MCP tools via Microsoft.Extensions.AI's IChatClient.

目次 (10)

Claude Is Available for .NET via NuGet — The Official Package Is "Anthropic"

The official route for calling Claude from a C# / .NET application is the NuGet package Anthropic. Anthropic officially states that "the Anthropic package at version 10 and above is the official C# SDK," providing easy C# access to the Anthropic REST API source.

The Anthropic package on the NuGet Gallery has over 1.5 million total downloads, is MIT licensed, is maintained by the official Anthropic account, and targets .NET Standard 2.0 and .NET 8.0 (compatible up to net9.0) source. Its broad coverage — from .NET Framework to the latest .NET — makes it easy to embed in legacy enterprise systems as well.

Note that it is currently in beta, meaning breaking changes may be introduced even in minor or patch updates. For production use, it is safer to pin the version and review the release notes on each upgrade.

Important: Versions 3.X and Below Are a Different Package — Move to tryAGI.Anthropic

Before searching for Anthropic on NuGet, there is a critical trap you must know about. The Anthropic package at version 3.X and below was not the official SDK — it was a separate package built by a community called tryAGI source.

The tryAGI version has since been migrated to a separate package called tryAGI.Anthropic. Here is a quick summary:

  • Anthropic (version 10 and above): Anthropic's official C# SDK. Use this for new projects.
  • Anthropic (version 3.X and below): The former tryAGI community version. It has served its purpose and is no longer maintained here.
  • tryAGI.Anthropic: The new home of the old tryAGI version. Change your reference here only if you need to keep using existing code.

If you follow an old article or sample and install Anthropic 3.X, it will not work because its API is completely different from the official SDK. When installing via NuGet, explicitly specify version 10 or later (the latest at the time of writing is in the 12.x range), or install using the equivalent of @latest.

Installation — dotnet add package Anthropic

Installation is a one-liner. Run the following at the root of your project source:

dotnet add package Anthropic

If you want to pin the version, specify it explicitly (in the format shown on the NuGet Gallery) source:

dotnet add package Anthropic --version 12.24.1

After installation, the following steps are a reliable way to verify everything is set up:

  1. Add the package with dotnet add package Anthropic.
  2. Confirm the version appears in PackageReference inside your .csproj.
  3. Set the ANTHROPIC_API_KEY environment variable (described below).
  4. Verify the project builds with dotnet build.
  5. Run the sample code and confirm you receive a response.

The only requirement is .NET Standard 2.0 or later — there are no special native dependencies. You can also add the package through Visual Studio's NuGet Package Manager UI by searching for Anthropic, but make sure to select version 10 or above in that case as well.

Minimal Code — Sending a Message with AnthropicClient

Once installed, the minimal setup is just a few lines source:

using System;
using Anthropic;
using Anthropic.Models.Messages;

AnthropicClient client = new();

MessageCreateParams parameters = new()
{
    MaxTokens = 1024,
    Messages =
    [
        new()
        {
            Role = Role.User,
            Content = "Hello, Claude",
        },
    ],
    Model = Model.ClaudeOpus4_8,
};

var message = await client.Messages.Create(parameters);

Console.WriteLine(message);

There are three key points. Instantiating AnthropicClient without arguments reads configuration from environment variables. You build a MessageCreateParams object and pass it to client.Messages.Create() — the return type is Task<Message>. Models are specified using typed constants like Model.ClaudeOpus4_8, which calls the latest Claude Opus 4.8.

MaxTokens is a required field, so do not forget to set it. To continue a conversation, accumulate the exchange history in the Messages array using Role.Assistant and Role.User.

API Key Setup — Environment Variables and Manual Configuration

Authentication is done via environment variables by default. Instantiating AnthropicClient without arguments automatically reads ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, and ANTHROPIC_BASE_URL source:

using Anthropic;

// Automatically configured from environment variables such as ANTHROPIC_API_KEY
AnthropicClient client = new();

If you need to pass values explicitly — for example, in CI or container environments — set them via properties:

using Anthropic;

AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };

The three configuration fields are ApiKey (env var ANTHROPIC_API_KEY), AuthToken (ANTHROPIC_AUTH_TOKEN), and BaseUrl (ANTHROPIC_BASE_URL, defaults to https://api.anthropic.com). For standard API key authentication, setting only ANTHROPIC_API_KEY is sufficient. ANTHROPIC_AUTH_TOKEN is for bearer token authentication such as OAuth flows. If you are using a standard API key issued from the Anthropic Console, only set ANTHROPIC_API_KEY. Hard-coding keys in source code is a leak risk, so always use environment variables or a secrets manager in production.

Streaming Responses — CreateStreaming and IAsyncEnumerable

If you want to display tokens one by one, as in a chat UI, use the streaming version of the method. Streaming method names always have a Streaming suffix, and the return type is IAsyncEnumerable source:

await foreach (var message in client.Messages.CreateStreaming(parameters))
{
    Console.WriteLine(message);
}

Iterating with await foreach lets you receive each chunk from the server as it arrives. Because rendering can start before the full response is ready, the perceived speed improves significantly. The SSE (Server-Sent Events)-based implementation also makes it straightforward to relay the stream directly to a client from a Web API.

IChatClient Integration — Microsoft.Extensions.AI and MCP

The official SDK implements the IChatClient interface from Microsoft.Extensions.AI.Abstractions. This lets you call Claude from generic code built on the standard .NET AI abstraction layer source:

using Anthropic;
using Microsoft.Extensions.AI;

AnthropicClient client = new();

IChatClient chatClient = client.AsIChatClient("claude-opus-4-8")
    .AsBuilder()
    .UseFunctionInvocation()
    .Build();

AsIChatClient() accepts the model ID as a string, so a string literal "claude-opus-4-8" is passed instead of the typed constant Model.ClaudeOpus4_8 used in the minimal code. Both refer to the same model — the difference is simply adapting to the argument type required by the IChatClient interface.

Once you can treat the client as an IChatClient, you can directly combine it with tools from the Model Context Protocol (MCP) C# SDK (ModelContextProtocol). For example, you can pass the tools exposed by an external MCP server to ChatOptions.Tools and use UseFunctionInvocation() to automate function calls — all with standard components. The biggest advantage of this abstraction is that the calling code does not need to change even if you swap out the provider.

Error Handling, Retries, and Timeouts

The official SDK throws dedicated exceptions for each HTTP status. The base class is AnthropicApiException, with subtypes such as AnthropicUnauthorizedException for 401, AnthropicRateLimitException for 429, and Anthropic5xxException for 5xx responses source. All 4xx exceptions inherit from Anthropic4xxException, so you can catch them together if needed.

Retries are performed automatically 2 times by default, with a short exponential backoff. They apply to connection errors, 408, 409, 429, and 5xx responses. To change the count, configure it on the client:

using Anthropic;

AnthropicClient client = new() { MaxRetries = 3 };

The default timeout is 10 minutes. For typical use cases that do not involve long-running streams or heavy generation, setting a shorter timeout for faster failure detection can make operations easier to manage:

using System;
using Anthropic;

AnthropicClient client = new() { Timeout = TimeSpan.FromSeconds(42) };

Using Claude via Cloud Platforms — Bedrock / Vertex / Foundry

Beyond calling the Anthropic API directly, separate NuGet packages are available for using Claude through cloud platforms source:

  • Amazon Bedrock: Anthropic.Bedrock (new projects should use AnthropicBedrockMantleClient)
  • Google Vertex AI: Anthropic.Vertex
  • Microsoft Foundry: Anthropic.Foundry (uses AnthropicFoundryClient)
  • Claude Platform on AWS: Anthropic.Aws (AnthropicAwsClient, beta)

Organizations that already run infrastructure on AWS, Google Cloud, or Azure can use these packages to consolidate authentication, billing, and data residency under their existing cloud contracts. Since the core API follows the same Messages.Create pattern, the learning curve when migrating from the direct API version is minimal.

Official Anthropic vs. Community Anthropic.SDK

In addition to the official Anthropic, NuGet also hosts a community package called Anthropic.SDK. This is an unofficial client developed by volunteers unaffiliated with Anthropic, with its own API design to make working with the Claude API in C# more convenient source:

Here is a guide for choosing between them:

  • New projects: Choose the official Anthropic. Officially maintained, with IChatClient integration built in.
  • Existing Anthropic.SDK assets: If it is working, there is no rush to migrate — plan the transition as needed.
  • Were using the old tryAGI version (Anthropic 3.X and below): Change your reference to tryAGI.Anthropic.

The official version is currently in beta, so its API may change, but if you are looking to integrate with the .NET ecosystem via IChatClient or planning to deploy to Bedrock / Vertex / Foundry, the official Anthropic is the top choice. Installation starts with a single dotnet add package Anthropic command — try the minimal code to confirm you get a response, then expand into streaming and tool integration from there source.

参考になったら ♡
Clauder Navi 編集部
@clauder_navi

Anthropic の Claude / Claude Code を中心に、日本のエンジニア向けに最新動向と実務 を毎日発信。 運営方針 は メディアについて をご覧ください。