Anthropic C# SDK

repository·main·Indexed 43 days ago

https://github.com/anthropics/anthropic-sdk-csharp

Official SDK for programmatic access to Claude and managed agent capabilities in .NET. Supports the Messages API via AnthropicClient and provides beta features for deploying managed agents, including cron scheduling, user-defined outcomes with evaluation rubrics, and MCP egress error handling. Requires .NET Standard 2.0+.

Tokens
6K
Snippets
22
Records
25
Agent score
55%

What's inside Anthropic C# SDK

  1. Get started with the Claude Messages API

    main

    To interact with Claude, instantiate an AnthropicClient and use the Messages.Create method. You must provide MessageCreateParams, which includes the Model name, MaxTokens limit, and a list of Messages containing the conversation history with specific Role assignments (e.g., Role.User).

    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 = "claude-opus-4-6",
    };
    
    var message = await client.Messages.Create(parameters);
    
    Console.WriteLine(message);
  2. Install the Anthropic SDK for C#

    main

    Install the official Claude SDK for C# using the NuGet package manager via the .NET CLI.

    Note on versioning: As of version 10+, the Anthropic package is the official SDK. If you are maintaining a legacy project that relies on the community-built tryAGI version (3.X and below), you should switch your package reference to tryAGI.Anthropic instead.

    dotnet add package Anthropic
  3. Handle Checkout variants in managed agents

    main

    The Checkout class is a discriminated union that can represent either a branch or a specific commit. To safely access the underlying data, use the TryPick, Switch, or Match methods.

    Pattern: TryPick

    Use TryPickBetaManagedAgentsBranch or TryPickBetaManagedAgentsCommit if you only care about one specific variant.

    Pattern: Switch

    Use Switch to execute different actions based on the variant without returning a value.

    Pattern: Match

    Use Match to transform the variant into a specific result type.

    // Using TryPick
    if (checkout.TryPickBetaManagedAgentsBranch(out var branch)) {
        Console.WriteLine($"Branch: {branch.Branch}");
    }
    
    // Using Switch
    checkout.Switch(
        branch => Console.WriteLine($"Branch: {branch.Branch}"),
        commit => Console.WriteLine($"Commit: {commit.Sha}")
    );
    
    // Using Match
    string description = checkout.Match(
        branch => $"Branch: {branch.Branch}",
        commit => $"Commit: {commit.Sha}"
    );
    // Example of using Match to handle Checkout variants
    var result = checkout.Match(
        (Sessions.BetaManagedAgentsBranchCheckout branch) => branch.Branch,
        (Sessions.BetaManagedAgentsCommitCheckout commit) => commit.Sha
    );
  4. Handle different Rubric variants

    main

    The Rubric class is a polymorphic type that can represent either a BetaManagedAgentsFileRubric or a BetaManagedAgentsTextRubric. To safely access the underlying data, use the following patterns:

    Using TryPick (for specific variants)

    Use TryPickBetaManagedAgentsFile or TryPickBetaManagedAgentsText if you only care about one specific type.

    Using Switch (for side effects)

    Use Switch to execute different logic based on the variant without returning a value.

    Using Match (to return a value)

    Use Match to transform the rubric into a different type based on its variant.

    Using Pattern Matching

    You can also use standard C# pattern matching on the Value property.

    // Using TryPick
    if (rubric.TryPickBetaManagedAgentsText(out var textRubric)) {
        // Handle text rubric
        Console.WriteLine(textRubric);
    }
    
    // Using Match to return a value
    string description = rubric.Match(
        betaManagedAgentsFile => $"File rubric: {betaManagedAgentsFile}",
        betaManagedAgentsText => $"Text rubric: {betaManagedAgentsText}"
    );
    
    // Using Switch for side effects
    rubric.Switch(
        betaManagedAgentsFile => Console.WriteLine("Processing file..."),
        betaManagedAgentsText => Console.WriteLine("Processing text...")
    );
  5. Handle Content variants in BetaManagedAgentsDeploymentUserMessageEvent

    main

    The Content class in a managed agent deployment is a polymorphic container that can hold different types of data: text, image, document, or redacted. To process these variants, you can use TryPick methods, Switch, or Match.

    Using TryPick

    Use TryPick... methods if you only care about one specific type of content.

    if (content.TryPickBetaManagedAgentsTextBlock(out var textBlock))
    {
        // Handle text block
        Console.WriteLine(textBlock);
    }

    Using Switch

    Use Switch to execute an action for every possible variant. This is useful for side effects.

    content.Switch(
        textBlock => { /* handle text */ },
        imageBlock => { /* handle image */ },
        documentBlock => { /* handle document */ },
        redactedBlock => { /* handle redacted */ }
    );

    Using Match

    Use Match when you need to transform the content into a specific return value. This is the preferred way to handle polymorphic data when mapping to a new type.

    string description = content.Match(
        textBlock => textBlock.Text, // Assuming Text property exists
        imageBlock => "An image",
        documentBlock => "A document",
        redactedBlock => "[REDACTED]"
    );
    // Example of using Match to extract a string from a Content object
    var result = content.Match(
        (Events::BetaManagedAgentsTextBlock value) => value.Text,
        (Events::BetaManagedAgentsImageBlock value) => "image",
        (Events::BetaManagedAgentsDocumentBlock value) => "document",
        (Events::BetaManagedAgentsRedactedBlock value) => "redacted"
    );
  6. Configure GitHub repository resources for managed agents

    main

    Use the BetaManagedAgentsGitHubRepositoryResourceConfig class to mount a GitHub repository into a session's container. This allows managed agents to access specific codebases.

    Properties

    • Type: Must be set to BetaManagedAgentsGitHubRepositoryResourceConfigType.GitHubRepository.
    • Url: The GitHub URL of the repository.
    • Checkout: (Optional) Specifies which branch or commit to check out. If omitted, the repository's default branch is used.
    • MountPath: (Optional) The path where the repository will be mounted in the container. Defaults to /workspace/<repo-name>.
    var config = new BetaManagedAgentsGitHubRepositoryResourceConfig
    {
        Type = BetaManagedAgentsGitHubRepositoryResourceConfigType.GitHubRepository,
        Url = "https://github.com/user/repo",
        Checkout = new Sessions.BetaManagedAgentsBranchCheckout { Branch = "main" },
        MountPath = "/app/code"
    };
  7. Configure file resources for Beta Managed Agents

    main

    When using Beta Managed Agents, you can mount previously uploaded files into a session's container using BetaManagedAgentsFileResourceConfig. This allows the agent to access specific files at a designated path within its environment.

    Properties

    PropertyTypeDescription
    FileIDstring (Required)The unique ID of a previously uploaded file.
    TypeBetaManagedAgentsFileResourceConfigType (Required)The type of resource. Currently, only BetaManagedAgentsFileResourceConfigType.File is supported.
    MountPathstring? (Optional)The path where the file will be mounted in the container. If not provided, it defaults to /mnt/session/uploads/<file_id> .

    Supported Types

    The Type property uses the BetaManagedAgentsFileResourceConfigType enum. Currently, the only valid value is:

    • BetaManagedAgentsFileResourceConfigType.File (serialized as "file")
    var fileConfig = new BetaManagedAgentsFileResourceConfig
    {
        FileID = "file_12345",
        Type = BetaManagedAgentsFileResourceConfigType.File,
        MountPath = "/custom/path/to/file"
    };
  8. Configure cron schedules for Managed Agents

    main

    Use the BetaManagedAgentsCronScheduleParams class to define a 5-field POSIX cron schedule for managed agents. This allows you to schedule agent tasks to run at specific times based on a literal wall-clock match in a configured timezone.

    Properties

    • Expression (required): A 5-field POSIX cron expression in the format minute hour day-of-month month day-of-week (e.g., "0 9 * * 1-5" for 9am on weekdays).
      • Note: Extended cron syntax (seconds, years, special characters like L, W, #, ?) and predefined shortcuts (like @daily) are not supported.
      • Day-of-week: Use 0-7, where both 0 and 7 represent Sunday.
    • Timezone (required): An IANA timezone identifier (e.g., "America/Los_Angeles" or "UTC"). This must be a valid identifier from the IANA timezone database.
    • Type (required): The type of schedule. For cron schedules, set this to BetaManagedAgentsCronScheduleParamsType.Cron.
    var cronSchedule = new BetaManagedAgentsCronScheduleParams
    {
        Expression = "0 9 * * 1-5",
        Timezone = "America/Los_Angeles",
        Type = BetaManagedAgentsCronScheduleParamsType.Cron
    };
  9. Handle Beta Managed Agents MCP egress blocked errors

    main

    When performing a deployment run for Beta Managed Agents, you may encounter a BetaManagedAgentsMcpEgressBlockedRunError. This error occurs when an MCP (Model Context Protocol) server host used by the deployment's agent is blocked by the environment's network policy.

    This error type contains the following properties:

    • Message: A human-readable description of the error.
    • Type: An enum of type BetaManagedAgentsMcpEgressBlockedRunErrorType which identifies the specific error category. For this error, the value is BetaManagedAgentsMcpEgressBlockedRunErrorType.McpEgressBlockedError (corresponding to the JSON string mcp_egress_blocked_error).
    // Example of handling the error (conceptual)
    try 
    {
        // Perform deployment run logic
    }
    catch (Exception ex) when (ex is BetaManagedAgentsMcpEgressBlockedRunError error)
    {
        Console.WriteLine($"Error Type: {error.Type}");
        Console.WriteLine($"Message: {error.Message}");
        // Handle the blocked egress scenario
    }
  10. Configure Beta Managed Agents Memory Store Resource

    main

    The BetaManagedAgentsMemoryStoreResourceConfig class is used to attach a memory store to sessions created from a managed agent deployment. This allows the agent to access persistent memory via a specific MemoryStoreID.

    Properties

    • MemoryStoreID (required): The unique identifier for the memory store (format: memstore_...). This ID must belong to the caller's organization and workspace.
    • Type (required): The type of resource. Currently, this only supports BetaManagedAgentsMemoryStoreResourceConfigType.MemoryStore (JSON value: memory_store).
    • Access (optional): The access mode for the attached store. Use Access.ReadWrite or Access.ReadOnly.
    • Instructions (optional): Guidance for the agent on how to use this specific store. This text is rendered into the memory section of the system prompt. It has a maximum length of 4096 characters.

    Usage Example

    var config = new BetaManagedAgentsMemoryStoreResourceConfig
    {
        MemoryStoreID = "memstore_example_id",
        Type = BetaManagedAgentsMemoryStoreResourceConfigType.MemoryStore,
        Access = Access.ReadWrite,
        Instructions = "Use this store to remember user preferences and past interaction context."
    };
  11. Define a user-defined outcome for managed agents

    main

    The BetaManagedAgentsDeploymentUserDefineOutcomeEvent class represents a task specification and grading criteria that a managed agent should work toward. When you provide this event, the agent begins work immediately.

    Key properties:

    • Description: A string specifying the task the agent should produce.
    • Rubric: A grading object used to evaluate the quality of the outcome.
    • Type: Must be BetaManagedAgentsDeploymentUserDefineOutcomeEventType.UserDefineOutcome.
    • MaxIterations (optional): The number of evaluation-to-revision cycles the agent should attempt before giving up. The default is 3, and the maximum is 20.
    var outcomeEvent = new BetaManagedAgentsDeploymentUserDefineOutcomeEvent
    {
        Description = "Generate a comprehensive report on Q3 sales trends.",
        Rubric = new BetaManagedAgentsTextRubric { /* ... rubric details ... */ },
        Type = BetaManagedAgentsDeploymentUserDefineOutcomeEventType.UserDefineOutcome,
        MaxIterations = 5
    };