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.
ruby/managed-agents/README.md
1# Managed Agents — Ruby23> **Bindings not shown here:** This README covers the most common managed-agents flows for Ruby. If you need a class, method, namespace, field, or behavior that isn't shown, WebFetch the Ruby 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 `client.beta.agents.create` and pass it to every subsequent `client.beta.sessions.create`; do not call `agents.create` 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```bash10gem install anthropic11```1213## Client Initialization1415```ruby16require "anthropic"1718# Default (uses ANTHROPIC_API_KEY env var)19client = Anthropic::Client.new2021# Explicit API key22client = Anthropic::Client.new(api_key: "your-api-key")23```2425> ⚠️ **Trailing underscores:** The Ruby SDK uses `system_:` and `send_(` (trailing underscore) to avoid shadowing `Kernel#system` and `Kernel#send`. Use these forms throughout managed-agents code.2627---2829## Create an Environment3031```ruby32environment = client.beta.environments.create(33name: "my-dev-env",34config: {35type: "cloud",36networking: {type: "unrestricted"}37}38)39puts "Environment ID: #{environment.id}" # env_...40```4142---4344## Create an Agent (required first step)4546> ⚠️ **There is no inline agent config.** `model`/`system_`/`tools` live on the agent object, not the session. Always start with `client.beta.agents.create()` — the session takes either `agent: agent.id` or the typed hash form `agent: {type: "agent", id: agent.id, version: agent.version}`.4748### Minimal4950```ruby51# 1. Create the agent (reusable, versioned)52agent = client.beta.agents.create(53name: "Coding Assistant",54model: :"claude-opus-4-7",55system_: "You are a helpful coding assistant.",56tools: [{type: "agent_toolset_20260401"}]57)5859# 2. Start a session60session = client.beta.sessions.create(61agent: {type: "agent", id: agent.id, version: agent.version},62environment_id: environment.id,63title: "Quickstart session"64)65puts "Session ID: #{session.id}"66```6768### Updating an Agent6970Updates create new versions; the agent object is immutable per version.7172```ruby73updated_agent = client.beta.agents.update(74agent.id,75version: agent.version,76system_: "You are a helpful coding agent. Always write tests."77)78puts "New version: #{updated_agent.version}"7980# List all versions81client.beta.agents.versions.list(agent.id).auto_paging_each do |version|82puts "Version #{version.version}: #{version.updated_at.iso8601}"83end8485# Archive the agent86archived = client.beta.agents.archive(agent.id)87puts "Archived at: #{archived.archived_at.iso8601}"88```8990---9192## Send a User Message9394```ruby95client.beta.sessions.events.send_(96session.id,97events: [{98type: "user.message",99content: [{type: "text", text: "Review the auth module"}]100}]101)102```103104> 💡 **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).105106---107108## Stream Events (SSE)109110```ruby111# Open the stream first, then send the user message112stream = client.beta.sessions.events.stream_events(session.id)113114client.beta.sessions.events.send_(115session.id,116events: [{117type: "user.message",118content: [{type: "text", text: "Summarize the repo README"}]119}]120)121122stream.each do |event|123case event.type124in :"agent.message"125event.content.each { |block| print block.text }126in :"agent.tool_use"127puts "\n[Using tool: #{event.name}]"128in :"session.status_idle"129break130in :"session.error"131puts "\n[Error: #{event.error&.message || "unknown"}]"132break133else134# ignore other event types135end136end137```138139> ℹ️ Event `.type` is a Symbol (compare with `:"agent.message"`, not `"agent.message"`).140141### Reconnecting and Tailing142143When reconnecting mid-session, list past events first to dedupe, then tail live events:144145```ruby146require "set"147148stream = client.beta.sessions.events.stream_events(session.id)149150# Stream is open and buffering. List history before tailing live.151seen_event_ids = Set.new152client.beta.sessions.events.list(session.id).auto_paging_each { |past| seen_event_ids << past.id }153154# Tail live events, skipping anything already seen155stream.each do |event|156next if seen_event_ids.include?(event.id)157seen_event_ids << event.id158case event.type159in :"agent.message"160event.content.each { |block| print block.text }161in :"session.status_idle"162break163else164# ignore other event types165end166end167```168169---170171## Provide Custom Tool Result172173> ℹ️ The Ruby 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 `anthropic` Ruby gem repository for the corresponding params.174175---176177## Poll Events178179```ruby180client.beta.sessions.events.list(session.id).auto_paging_each do |event|181puts "#{event.type}: #{event.id}"182end183```184185---186187## Upload a File188189```ruby190require "pathname"191192file = client.beta.files.upload(file: Pathname("data.csv"))193puts "File ID: #{file.id}"194195# Mount in a session196session = client.beta.sessions.create(197agent: agent.id,198environment_id: environment.id,199resources: [200{201type: "file",202file_id: file.id,203mount_path: "/workspace/data.csv"204}205]206)207```208209### Add and Manage Resources on an Existing Session210211```ruby212# Attach an additional file to an open session213resource = client.beta.sessions.resources.add(214session.id,215type: "file",216file_id: file.id217)218puts resource.id # "sesrsc_01ABC..."219220# List resources on the session221listed = client.beta.sessions.resources.list(session.id)222listed.data.each { |entry| puts "#{entry.id} #{entry.type}" }223224# Detach a resource225client.beta.sessions.resources.delete(resource.id, session_id: session.id)226```227228---229230## List and Download Session Files231232> ℹ️ Listing and downloading files an agent wrote during a session is not yet documented for Ruby in this skill or in the apps source examples. See `shared/managed-agents-events.md` and the `anthropic` Ruby gem repository for the file list/download bindings.233234---235236## Session Management237238```ruby239# List environments240environments = client.beta.environments.list241242# Retrieve a specific environment243env = client.beta.environments.retrieve(environment.id)244245# Archive an environment (read-only, existing sessions continue)246client.beta.environments.archive(environment.id)247248# Delete an environment (only if no sessions reference it)249client.beta.environments.delete(environment.id)250251# Delete a session252client.beta.sessions.delete(session.id)253```254255---256257## MCP Server Integration258259```ruby260# Agent declares MCP server (no auth here — auth goes in a vault)261agent = client.beta.agents.create(262name: "GitHub Assistant",263model: :"claude-opus-4-7",264mcp_servers: [265{266type: "url",267name: "github",268url: "https://api.githubcopilot.com/mcp/"269}270],271tools: [272{type: "agent_toolset_20260401"},273{type: "mcp_toolset", mcp_server_name: "github"}274]275)276277# Session attaches vault(s) containing credentials for those MCP server URLs278session = client.beta.sessions.create(279agent: {type: "agent", id: agent.id, version: agent.version},280environment_id: environment.id,281vault_ids: [vault.id]282)283```284285See `shared/managed-agents-tools.md` §Vaults for creating vaults and adding credentials.286287---288289## Vaults290291```ruby292# Create a vault293vault = client.beta.vaults.create(294display_name: "Alice",295metadata: {external_user_id: "usr_abc123"}296)297puts vault.id # "vlt_01ABC..."298299# Add an OAuth credential300credential = client.beta.vaults.credentials.create(301vault.id,302display_name: "Alice's Slack",303auth: {304type: "mcp_oauth",305mcp_server_url: "https://mcp.slack.com/mcp",306access_token: "xoxp-...",307expires_at: "2026-04-15T00:00:00Z",308refresh: {309token_endpoint: "https://slack.com/api/oauth.v2.access",310client_id: "1234567890.0987654321",311scope: "channels:read chat:write",312refresh_token: "xoxe-1-...",313token_endpoint_auth: {314type: "client_secret_post",315client_secret: "abc123..."316}317}318}319)320321# Rotate the credential (e.g., after a token refresh)322client.beta.vaults.credentials.update(323credential.id,324vault_id: vault.id,325auth: {326type: "mcp_oauth",327access_token: "xoxp-new-...",328expires_at: "2026-05-15T00:00:00Z",329refresh: {refresh_token: "xoxe-1-new-..."}330}331)332333# Archive a vault334client.beta.vaults.archive(vault.id)335```336337---338339## GitHub Repository Integration340341Mount a GitHub repository as a session resource (a vault holds the GitHub MCP credential):342343```ruby344session = client.beta.sessions.create(345agent: agent.id,346environment_id: environment.id,347vault_ids: [vault.id],348resources: [349{350type: "github_repository",351url: "https://github.com/org/repo",352mount_path: "/workspace/repo",353authorization_token: "ghp_your_github_token"354}355]356)357```358359Multiple repositories on the same session:360361```ruby362resources = [363{364type: "github_repository",365url: "https://github.com/org/frontend",366mount_path: "/workspace/frontend",367authorization_token: "ghp_your_github_token"368},369{370type: "github_repository",371url: "https://github.com/org/backend",372mount_path: "/workspace/backend",373authorization_token: "ghp_your_github_token"374}375]376```377378Rotating a repository's authorization token:379380```ruby381listed = client.beta.sessions.resources.list(session.id)382repo_resource_id = listed.data.first.id383384client.beta.sessions.resources.update(385repo_resource_id,386session_id: session.id,387authorization_token: "ghp_your_new_github_token"388)389```390