Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
go/managed-agents/README.md
1# Managed Agents — Go23> **Bindings not shown here:** This README covers the most common managed-agents flows for Go. If you need a class, method, namespace, field, or behavior that isn't shown, WebFetch the Go SDK repo **or the relevant docs page** from `shared/live-sources.md` rather than guess. Do not extrapolate from cURL shapes or another language's SDK.45> **Agents are persistent — create once, reference by ID.** Store the agent ID returned by `agents.New` and pass it to every subsequent `sessions.New`; do not call `agents.New` in the request path. The Anthropic CLI is one convenient way to create agents and environments from version-controlled YAML — its URL is in `shared/live-sources.md`. The examples below show in-code creation for completeness; in production the create call belongs in setup, not in the request path.67## Installation89```bash10go get github.com/anthropics/anthropic-sdk-go11```1213## Client Initialization1415```go16import (17"context"1819"github.com/anthropics/anthropic-sdk-go"20"github.com/anthropics/anthropic-sdk-go/option"21)2223// Default (uses ANTHROPIC_API_KEY env var)24client := anthropic.NewClient()2526// Explicit API key27client := anthropic.NewClient(28option.WithAPIKey("your-api-key"),29)3031ctx := context.Background()32```3334---3536## Create an Environment3738```go39environment, err := client.Beta.Environments.New(ctx, anthropic.BetaEnvironmentNewParams{40Name: "my-dev-env",41Config: anthropic.BetaCloudConfigParams{42Networking: anthropic.BetaCloudConfigParamsNetworkingUnion{43OfUnrestricted: &anthropic.UnrestrictedNetworkParam{},44},45},46})47if err != nil {48panic(err)49}50fmt.Println(environment.ID) // env_...51```5253---5455## Create an Agent (required first step)5657> ⚠️ **There is no inline agent config.** `Model`/`System`/`Tools` live on the agent object, not the session. Always start with `Beta.Agents.New()` — the session only takes `Agent: anthropic.BetaSessionNewParamsAgentUnion{OfString: anthropic.String(agent.ID)}` (or the typed `OfBetaManagedAgentsAgents` variant when you need a specific version).5859### Minimal6061```go62// 1. Create the agent (reusable, versioned)63agent, err := client.Beta.Agents.New(ctx, anthropic.BetaAgentNewParams{64Name: "Coding Assistant",65Model: anthropic.BetaManagedAgentsModelConfigParams{66ID: "claude-opus-4-7",67Type: anthropic.BetaManagedAgentsModelConfigParamsTypeModelConfig,68},69System: anthropic.String("You are a helpful coding assistant."),70Tools: []anthropic.BetaAgentNewParamsToolUnion{{71OfAgentToolset20260401: &anthropic.BetaManagedAgentsAgentToolset20260401Params{72Type: anthropic.BetaManagedAgentsAgentToolset20260401ParamsTypeAgentToolset20260401,73},74}},75})76if err != nil {77panic(err)78}7980// 2. Start a session81session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{82Agent: anthropic.BetaSessionNewParamsAgentUnion{83OfBetaManagedAgentsAgents: &anthropic.BetaManagedAgentsAgentParams{84Type: anthropic.BetaManagedAgentsAgentParamsTypeAgent,85ID: agent.ID,86Version: anthropic.Int(agent.Version),87},88},89EnvironmentID: environment.ID,90Title: anthropic.String("Quickstart session"),91})92if err != nil {93panic(err)94}95fmt.Printf("Session ID: %s, status: %s\n", session.ID, session.Status)96```9798### Updating an Agent99100Updates create new versions; the agent object is immutable per version.101102```go103updatedAgent, err := client.Beta.Agents.Update(ctx, agent.ID, anthropic.BetaAgentUpdateParams{104Version: agent.Version,105System: anthropic.String("You are a helpful coding agent. Always write tests."),106})107if err != nil {108panic(err)109}110fmt.Printf("New version: %d\n", updatedAgent.Version)111112// List all versions113iter := client.Beta.Agents.Versions.ListAutoPaging(ctx, agent.ID, anthropic.BetaAgentVersionListParams{})114for iter.Next() {115version := iter.Current()116fmt.Printf("Version %d: %s\n", version.Version, version.UpdatedAt.Format(time.RFC3339))117}118if err := iter.Err(); err != nil {119panic(err)120}121122// Archive the agent123_, err = client.Beta.Agents.Archive(ctx, agent.ID, anthropic.BetaAgentArchiveParams{})124if err != nil {125panic(err)126}127```128129---130131## Send a User Message132133```go134_, err = client.Beta.Sessions.Events.Send(ctx, session.ID, anthropic.BetaSessionEventSendParams{135Events: []anthropic.SendEventsParamsUnion{{136OfUserMessage: &anthropic.BetaManagedAgentsUserMessageEventParams{137Type: anthropic.BetaManagedAgentsUserMessageEventParamsTypeUserMessage,138Content: []anthropic.BetaManagedAgentsUserMessageEventParamsContentUnion{{139OfText: &anthropic.BetaManagedAgentsTextBlockParam{140Type: anthropic.BetaManagedAgentsTextBlockTypeText,141Text: "Review the auth module",142},143}},144},145}},146})147if err != nil {148panic(err)149}150```151152> 💡 **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens — stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).153154---155156## Stream Events (SSE)157158```go159// Open the stream first, then send the user message160stream := client.Beta.Sessions.Events.StreamEvents(ctx, session.ID, anthropic.BetaSessionEventStreamParams{})161defer stream.Close()162163if _, err := client.Beta.Sessions.Events.Send(ctx, session.ID, anthropic.BetaSessionEventSendParams{164Events: []anthropic.SendEventsParamsUnion{{165OfUserMessage: &anthropic.BetaManagedAgentsUserMessageEventParams{166Type: anthropic.BetaManagedAgentsUserMessageEventParamsTypeUserMessage,167Content: []anthropic.BetaManagedAgentsUserMessageEventParamsContentUnion{{168OfText: &anthropic.BetaManagedAgentsTextBlockParam{169Type: anthropic.BetaManagedAgentsTextBlockTypeText,170Text: "Summarize the repo README",171},172}},173},174}},175}); err != nil {176panic(err)177}178179events:180for stream.Next() {181switch event := stream.Current().AsAny().(type) {182case anthropic.BetaManagedAgentsAgentMessageEvent:183for _, block := range event.Content {184fmt.Print(block.Text)185}186case anthropic.BetaManagedAgentsAgentToolUseEvent:187fmt.Printf("\n[Using tool: %s]\n", event.Name)188case anthropic.BetaManagedAgentsSessionStatusIdleEvent:189break events190case anthropic.BetaManagedAgentsSessionErrorEvent:191fmt.Printf("\n[Error: %s]\n", event.Error.Message)192break events193}194}195if err := stream.Err(); err != nil {196panic(err)197}198```199200### Reconnecting and Tailing201202When reconnecting mid-session, list past events first to dedupe, then tail live events:203204```go205stream := client.Beta.Sessions.Events.StreamEvents(ctx, session.ID, anthropic.BetaSessionEventStreamParams{})206defer stream.Close()207208// Stream is open and buffering. List history before tailing live.209seenEventIDs := map[string]struct{}{}210history := client.Beta.Sessions.Events.ListAutoPaging(ctx, session.ID, anthropic.BetaSessionEventListParams{})211for history.Next() {212seenEventIDs[history.Current().ID] = struct{}{}213}214if err := history.Err(); err != nil {215panic(err)216}217218// Tail live events, skipping anything already seen219tail:220for stream.Next() {221event := stream.Current()222if _, seen := seenEventIDs[event.ID]; seen {223continue224}225seenEventIDs[event.ID] = struct{}{}226switch event := event.AsAny().(type) {227case anthropic.BetaManagedAgentsAgentMessageEvent:228for _, block := range event.Content {229fmt.Print(block.Text)230}231case anthropic.BetaManagedAgentsSessionStatusIdleEvent:232break tail233}234}235if err := stream.Err(); err != nil {236panic(err)237}238```239240---241242## Provide Custom Tool Result243244> ℹ️ The Go managed-agents bindings for `user.custom_tool_result` are not yet documented in this skill or in the apps source examples. Refer to `shared/managed-agents-events.md` for the wire format and the `github.com/anthropics/anthropic-sdk-go` repository for the corresponding Go params types.245246---247248## Poll Events249250```go251// Auto-paginating iterator252iter := client.Beta.Sessions.Events.ListAutoPaging(ctx, session.ID, anthropic.BetaSessionEventListParams{})253for iter.Next() {254event := iter.Current()255fmt.Printf("%s: %s\n", event.Type, event.ID)256}257if err := iter.Err(); err != nil {258panic(err)259}260```261262---263264## Upload a File265266```go267csvFile, err := os.Open("data.csv")268if err != nil {269panic(err)270}271defer csvFile.Close()272273file, err := client.Beta.Files.Upload(ctx, anthropic.BetaFileUploadParams{274File: csvFile,275})276if err != nil {277panic(err)278}279fmt.Printf("File ID: %s\n", file.ID)280281// Mount in a session282session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{283Agent: anthropic.BetaSessionNewParamsAgentUnion{284OfString: anthropic.String(agent.ID),285},286EnvironmentID: environment.ID,287Resources: []anthropic.BetaSessionNewParamsResourceUnion{{288OfFile: &anthropic.BetaManagedAgentsFileResourceParams{289Type: anthropic.BetaManagedAgentsFileResourceParamsTypeFile,290FileID: file.ID,291MountPath: anthropic.String("/workspace/data.csv"),292},293}},294})295if err != nil {296panic(err)297}298```299300### Add and Manage Resources on an Existing Session301302```go303// Attach an additional file to an open session304resource, err := client.Beta.Sessions.Resources.Add(ctx, session.ID, anthropic.BetaSessionResourceAddParams{305BetaManagedAgentsFileResourceParams: anthropic.BetaManagedAgentsFileResourceParams{306Type: anthropic.BetaManagedAgentsFileResourceParamsTypeFile,307FileID: file.ID,308},309})310if err != nil {311panic(err)312}313fmt.Println(resource.ID) // "sesrsc_01ABC..."314315// List resources on the session316listed, err := client.Beta.Sessions.Resources.List(ctx, session.ID, anthropic.BetaSessionResourceListParams{})317if err != nil {318panic(err)319}320for _, entry := range listed.Data {321fmt.Println(entry.ID, entry.Type)322}323324// Detach a resource325if _, err := client.Beta.Sessions.Resources.Delete(ctx, resource.ID, anthropic.BetaSessionResourceDeleteParams{326SessionID: session.ID,327}); err != nil {328panic(err)329}330```331332---333334## List and Download Session Files335336> ℹ️ Listing and downloading files an agent wrote during a session is not yet documented for Go in this skill or in the apps source examples. See `shared/managed-agents-events.md` and the `github.com/anthropics/anthropic-sdk-go` repository for the `Beta.Files.List` and `Beta.Files.Download` Go params types.337338---339340## Session Management341342```go343// List environments344environments, err := client.Beta.Environments.List(ctx, anthropic.BetaEnvironmentListParams{})345if err != nil {346panic(err)347}348349// Retrieve a specific environment350env, err := client.Beta.Environments.Get(ctx, environment.ID, anthropic.BetaEnvironmentGetParams{})351if err != nil {352panic(err)353}354355// Archive an environment (read-only, existing sessions continue)356_, err = client.Beta.Environments.Archive(ctx, environment.ID, anthropic.BetaEnvironmentArchiveParams{})357if err != nil {358panic(err)359}360361// Delete an environment (only if no sessions reference it)362_, err = client.Beta.Environments.Delete(ctx, environment.ID, anthropic.BetaEnvironmentDeleteParams{})363if err != nil {364panic(err)365}366367// Delete a session368_, err = client.Beta.Sessions.Delete(ctx, session.ID, anthropic.BetaSessionDeleteParams{})369if err != nil {370panic(err)371}372```373374---375376## MCP Server Integration377378```go379// Agent declares MCP server (no auth here — auth goes in a vault)380agent, err := client.Beta.Agents.New(ctx, anthropic.BetaAgentNewParams{381Name: "GitHub Assistant",382Model: anthropic.BetaManagedAgentsModelConfigParams{383ID: "claude-opus-4-7",384Type: anthropic.BetaManagedAgentsModelConfigParamsTypeModelConfig,385},386MCPServers: []anthropic.BetaManagedAgentsUrlmcpServerParams{{387Type: anthropic.BetaManagedAgentsUrlmcpServerParamsTypeURL,388Name: "github",389URL: "https://api.githubcopilot.com/mcp/",390}},391Tools: []anthropic.BetaAgentNewParamsToolUnion{392{393OfAgentToolset20260401: &anthropic.BetaManagedAgentsAgentToolset20260401Params{394Type: anthropic.BetaManagedAgentsAgentToolset20260401ParamsTypeAgentToolset20260401,395},396},397{398OfMCPToolset: &anthropic.BetaManagedAgentsMCPToolsetParams{399Type: anthropic.BetaManagedAgentsMCPToolsetParamsTypeMCPToolset,400MCPServerName: "github",401},402},403},404})405if err != nil {406panic(err)407}408409// Session attaches vault(s) containing credentials for those MCP server URLs410session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{411Agent: anthropic.BetaSessionNewParamsAgentUnion{412OfBetaManagedAgentsAgents: &anthropic.BetaManagedAgentsAgentParams{413Type: anthropic.BetaManagedAgentsAgentParamsTypeAgent,414ID: agent.ID,415Version: anthropic.Int(agent.Version),416},417},418EnvironmentID: environment.ID,419VaultIDs: []string{vault.ID},420})421if err != nil {422panic(err)423}424```425426See `shared/managed-agents-tools.md` §Vaults for creating vaults and adding credentials.427428---429430## Vaults431432```go433// Create a vault434vault, err := client.Beta.Vaults.New(ctx, anthropic.BetaVaultNewParams{435DisplayName: "Alice",436Metadata: map[string]string{"external_user_id": "usr_abc123"},437})438if err != nil {439panic(err)440}441442// Add an OAuth credential443credential, err := client.Beta.Vaults.Credentials.New(ctx, vault.ID, anthropic.BetaVaultCredentialNewParams{444DisplayName: anthropic.String("Alice's Slack"),445Auth: anthropic.BetaVaultCredentialNewParamsAuthUnion{446OfMCPOAuth: &anthropic.BetaManagedAgentsMCPOAuthCreateParams{447Type: anthropic.BetaManagedAgentsMCPOAuthCreateParamsTypeMCPOAuth,448MCPServerURL: "https://mcp.slack.com/mcp",449AccessToken: "xoxp-...",450ExpiresAt: anthropic.Time(time.Date(2026, time.April, 15, 0, 0, 0, 0, time.UTC)),451Refresh: anthropic.BetaManagedAgentsMCPOAuthRefreshParams{452TokenEndpoint: "https://slack.com/api/oauth.v2.access",453ClientID: "1234567890.0987654321",454Scope: anthropic.String("channels:read chat:write"),455RefreshToken: "xoxe-1-...",456TokenEndpointAuth: anthropic.BetaManagedAgentsMCPOAuthRefreshParamsTokenEndpointAuthUnion{457OfClientSecretPost: &anthropic.BetaManagedAgentsTokenEndpointAuthPostParam{458Type: anthropic.BetaManagedAgentsTokenEndpointAuthPostParamTypeClientSecretPost,459ClientSecret: "abc123...",460},461},462},463},464},465})466if err != nil {467panic(err)468}469470// Rotate the credential (e.g., after a token refresh)471_, err = client.Beta.Vaults.Credentials.Update(ctx, credential.ID, anthropic.BetaVaultCredentialUpdateParams{472VaultID: vault.ID,473Auth: anthropic.BetaVaultCredentialUpdateParamsAuthUnion{474OfMCPOAuth: &anthropic.BetaManagedAgentsMCPOAuthUpdateParams{475Type: anthropic.BetaManagedAgentsMCPOAuthUpdateParamsTypeMCPOAuth,476AccessToken: anthropic.String("xoxp-new-..."),477ExpiresAt: anthropic.Time(time.Date(2026, time.May, 15, 0, 0, 0, 0, time.UTC)),478Refresh: anthropic.BetaManagedAgentsMCPOAuthRefreshUpdateParams{479RefreshToken: anthropic.String("xoxe-1-new-..."),480},481},482},483})484if err != nil {485panic(err)486}487488// Archive a vault489_, err = client.Beta.Vaults.Archive(ctx, vault.ID, anthropic.BetaVaultArchiveParams{})490if err != nil {491panic(err)492}493```494495---496497## GitHub Repository Integration498499Mount a GitHub repository as a session resource (a vault holds the GitHub MCP credential):500501```go502session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{503Agent: anthropic.BetaSessionNewParamsAgentUnion{OfString: anthropic.String(agent.ID)},504EnvironmentID: environment.ID,505VaultIDs: []string{vault.ID},506Resources: []anthropic.BetaSessionNewParamsResourceUnion{507{508OfGitHubRepository: &anthropic.BetaManagedAgentsGitHubRepositoryResourceParams{509Type: anthropic.BetaManagedAgentsGitHubRepositoryResourceParamsTypeGitHubRepository,510URL: "https://github.com/org/repo",511MountPath: anthropic.String("/workspace/repo"),512AuthorizationToken: "ghp_your_github_token",513},514},515},516})517if err != nil {518panic(err)519}520```521522Multiple repositories on the same session:523524```go525resources := []anthropic.BetaSessionNewParamsResourceUnion{526{527OfGitHubRepository: &anthropic.BetaManagedAgentsGitHubRepositoryResourceParams{528Type: anthropic.BetaManagedAgentsGitHubRepositoryResourceParamsTypeGitHubRepository,529URL: "https://github.com/org/frontend",530MountPath: anthropic.String("/workspace/frontend"),531AuthorizationToken: "ghp_your_github_token",532},533},534{535OfGitHubRepository: &anthropic.BetaManagedAgentsGitHubRepositoryResourceParams{536Type: anthropic.BetaManagedAgentsGitHubRepositoryResourceParamsTypeGitHubRepository,537URL: "https://github.com/org/backend",538MountPath: anthropic.String("/workspace/backend"),539AuthorizationToken: "ghp_your_github_token",540},541},542}543```544545Rotating a repository's authorization token:546547```go548listed, err := client.Beta.Sessions.Resources.List(ctx, session.ID, anthropic.BetaSessionResourceListParams{})549if err != nil {550panic(err)551}552repoResourceID := listed.Data[0].ID553554_, err = client.Beta.Sessions.Resources.Update(ctx, repoResourceID, anthropic.BetaSessionResourceUpdateParams{555SessionID: session.ID,556AuthorizationToken: "ghp_your_new_github_token",557})558if err != nil {559panic(err)560}561```562