Claude Agent Ruby SDK
Overview
Use this skill to build or refactor Ruby integrations with Claude Code via claude-agent-sdk, favoring the gem's README, the docs/ topic subpages, and lib/ types for exact APIs.
Decision Guide
- Choose
ClaudeAgentSDK.queryfor one-shot queries or streaming input. Internally uses the control protocol (streaming mode). - Choose
ClaudeAgentSDK::Clientfor multi-turn sessions, hooks, permission callbacks, MCP server control, or dynamic model switching; wrap inAsync do ... end.wait. - Choose SDK MCP servers (
create_tool,create_sdk_mcp_server) for in-process tools; choose external MCP configs for subprocess/HTTP servers. - Choose
ClaudeAgentSDK.list_sessions/ClaudeAgentSDK.get_session_messagesfor browsing previous session transcripts (pure filesystem, no CLI needed).
Implementation Checklist
- Confirm prerequisites (Ruby 3.2+, Node.js, Claude Code CLI).
- Build
ClaudeAgentSDK::ClaudeAgentOptionsand pass it toqueryorClient.new. - Handle messages by type — the SDK has 26 typed message classes:
- Core:
AssistantMessage,UserMessage,ResultMessage,StreamEvent,RateLimitEvent - System init:
InitMessage(session start / /clear — carries uuid, session_id, tools, model, cwd, agents, betas, claude_code_version, permission_mode, slash_commands, output_style, skills, plugins, fast_mode_state) - Compaction:
CompactBoundaryMessage(uuid, session_id, compact_metadata with pre_tokens, trigger, preserved_segment) - Status:
StatusMessage(compacting status, permission mode changes) - Tasks:
TaskStartedMessage(+ workflow_name, prompt),TaskProgressMessage(+ summary),TaskNotificationMessage,TaskUpdatedMessage(lifecycle state change;statusderived frompatch['status'],task_idalways a String — clear active-task tracking whenstatusis inTERMINAL_TASK_STATUSES) - Hooks:
HookStartedMessage,HookProgressMessage,HookResponseMessage - Sessions:
SessionStateChangedMessage(idle/running/requires_action) - Tools:
ToolProgressMessage(elapsed_time_seconds per tool),ToolUseSummaryMessage - Auth:
AuthStatusMessage(isAuthenticating, output, error) - Files:
FilesPersistedMessage(files, failed, processed_at) - API:
APIRetryMessage(attempt, max_retries, retry_delay_ms, error_status) - Session store:
MirrorErrorMessage(a SessionStore append failed after retries — session continues; local transcript stays durable) - Other:
LocalCommandOutputMessage,ElicitationCompleteMessage,PromptSuggestionMessage - Unknown message types return
nil(forward-compatible)
- Core:
- Handle content blocks:
TextBlock,ThinkingBlock,ToolUseBlock,ToolResultBlock,UnknownBlock AssistantMessagecarries:content,model,parent_tool_use_id,error,usage,message_id(API message ID),stop_reason,session_id,uuid(transcript UUID)ResultMessagecarries:stop_reason,model_usage(per-model breakdown),permission_denials,errors(on error subtypes),uuid,fast_mode_state- Use
output_formatfor JSON schema structured output - Use
thinking:withThinkingConfigAdaptive,ThinkingConfigEnabled(budget_tokens:), orThinkingConfigDisabled. Useeffort:for effort level.
Hooks (27 events)
All hook events: PreToolUse, PostToolUse, PostToolUseFailure, Notification, UserPromptSubmit, SessionStart, SessionEnd, Stop, StopFailure, SubagentStart, SubagentStop, PreCompact, PostCompact, PermissionRequest, PermissionDenied, Setup, TeammateIdle, TaskCreated, TaskCompleted, Elicitation, ElicitationResult, ConfigChange, WorktreeCreate, WorktreeRemove, InstructionsLoaded, CwdChanged, FileChanged.
Define hooks as Ruby procs/lambdas. Do not combine can_use_tool with permission_prompt_tool_name. Tool-lifecycle hooks carry agent_id and agent_type when firing inside subagents. StopHookInput and SubagentStopHookInput include last_assistant_message.
Hook-specific outputs with to_h: PreToolUseHookSpecificOutput, PostToolUseHookSpecificOutput, PostToolUseFailureHookSpecificOutput, UserPromptSubmitHookSpecificOutput, NotificationHookSpecificOutput, SubagentStartHookSpecificOutput, SessionStartHookSpecificOutput, SetupHookSpecificOutput, PermissionRequestHookSpecificOutput, PermissionDeniedHookSpecificOutput, CwdChangedHookSpecificOutput, FileChangedHookSpecificOutput.
Bare Mode
Use bare: true for minimal startup — skips hooks, LSP, plugin sync, CLAUDE.md auto-discovery, auto-memory, keychain reads. Explicitly provide context via system_prompt, add_dirs, setting_sources, allowed_tools.
options = ClaudeAgentSDK::ClaudeAgentOptions.new(
bare: true,
system_prompt: 'You are a code reviewer.',
permission_mode: 'bypassPermissions'
)
Sandbox Settings (full CC parity)
SandboxSettings: enabled, fail_if_unavailable, auto_allow_bash_if_sandboxed, excluded_commands, allow_unsandboxed_commands, network, filesystem, ignore_violations (Hash), enable_weaker_nested_sandbox, enable_weaker_network_isolation, ripgrepSandboxNetworkConfig: allowed_domains, denied_domains, allow_managed_domains_only, allow_unix_sockets, allow_all_unix_sockets, allow_local_binding, allow_mach_lookup, http_proxy_port, socks_proxy_portSandboxFilesystemConfig: allow_write, deny_write, deny_read, allow_read, allow_managed_read_paths_only
SDK MCP Tools
- Include
mcp__<server>__<tool>inallowed_tools - Use
annotations:oncreate_toolfor MCP tool annotations - Use
meta:oncreate_toolfor_metafield forwarding (e.g.,{ 'anthropic/maxResultSizeChars' => 100000 }to prevent truncation of large results) - If
annotations[:maxResultSizeChars]is set,_metais auto-populated - Both symbol-keyed and string-keyed
input_schemahashes are accepted
Session Management
resume,session_id,fork_sessionoption for session handlingClaudeAgentSDK.delete_session(session_id:, directory:)— hard-deletes a sessionClaudeAgentSDK.fork_session(session_id:, directory:, up_to_message_id:, title:)→ForkSessionResult— filesystem fork with UUID remappingClaudeAgentSDK.list_sessions(directory:, limit:, offset:, include_worktrees:)— supportsoffsetfor paginationClaudeAgentSDK.list_subagents(session_id:, directory:)/ClaudeAgentSDK.get_subagent_messages(session_id:, agent_id:, directory:, limit:, offset:)— local-disk subagent transcript readers (disk counterparts of the*_from_storepair)- SessionStore mirroring:
ClaudeAgentOptions.new(session_store: store)mirrors transcripts to external storage (subclassClaudeAgentSDK::SessionStore— only#append/#loadrequired;InMemorySessionStorefor tests; S3/Redis/Postgres reference adapters inexamples/session_stores/).session_store_flush: 'eager'flushes per frame;load_timeout_msbounds resume store calls. - Resume from store: pair
session_storewithresume:/continue_conversation— no local JSONL needed. Note: runs the CLI against a bare tempCLAUDE_CONFIG_DIR(user-scope settings.json/agents/skills invisible; project.claude/*still applies). - Store-backed helpers:
list_sessions_from_store,get_session_info_from_store,get_session_messages_from_store,list_subagents_from_store,get_subagent_messages_from_store,rename_session_via_store,tag_session_via_store,delete_session_via_store,fork_session_via_store,import_session_to_store(migrate disk → store). Store reads defaultdirectory:to cwd. Validate adapters withClaudeAgentSDK::Testing.run_session_store_conformance. Client#get_context_usage— context window breakdown (tokens by category, model, MCP tools, etc.)Client#reconnect_mcp_server(name),Client#toggle_mcp_server(name, enabled),Client#stop_task(task_id)for live controlClient#rewind_files(uuid)withenable_file_checkpointing: trueMcpStatusResponse.parse(client.get_mcp_status)for typed MCP status
Where To Look For Exact Details
- Locate the gem:
bundle show claude-agent-sdk - Read
<gem_path>/README.mdfor the overview, install, and minimal API examples - Read
<gem_path>/docs/*.mdfor topic subpages —client.md(bidirectional + custom transports),mcp-servers.md(SDK MCP tools/resources/prompts),hooks-and-permissions.md(27 hook events + permission callbacks),configuration.md(structured output, thinking, budget, sandbox, bare mode, file checkpointing),sessions.md(list/read/rename/tag/fork/resume + SessionStore mirroring/store-backed helpers),observability.md(OTel + Langfuse),rails.md(ActionCable, jobs, initializers),types.md(message/content-block/configuration types),errors.md(error hierarchy + timeout) - Inspect
<gem_path>/lib/claude_agent_sdk/types.rbfor all types - Inspect
<gem_path>/lib/claude_agent_sdk/message_parser.rbfor message parsing - Inspect
<gem_path>/lib/claude_agent_sdk/sessions.rbfor session browsing - Inspect
<gem_path>/lib/claude_agent_sdk/errors.rbfor error classes - Use
references/usage-map.mdfor a documentation map (README + docs/) and minimal skeletons
Resources
references/
- Read
references/usage-map.mdto map tasks to README anddocs/subpages, gem paths, and minimal skeletons. - Read
references/message-handling.mdto extract text/tool blocks, build streaming input, use Client runtime APIs, and capture UUIDs for rewind. - Read
references/options.mdto configureClaudeAgentOptions(defaults, tools, permissions, skills, output formats, budgets, sandbox, sessions, agents, custom transports), and to browse/mutate sessions. - Read
references/mcp-servers.mdto define in-process SDK MCP tools/resources/prompts, configure external MCP servers, or manage MCP servers at runtime. - Read
references/rails.mdfor initializers, background jobs, ActionCable streaming, and session resumption patterns. - Read
references/troubleshooting.mdfor common setup/runtime errors and timeout tuning.