Sandbox
@ya-luotao/claude-agent-sdk-ruby

Ruby SDK for Claude Code agents and tools

This gem wraps the Claude Code CLI so Ruby code can start one-shot queries or keep a bidirectional session open. It also exposes custom tools, hooks, permission callbacks, session control, observability, and Rails-friendly integration points.

48 stars5 forksRubyUpdated 10d ago
Who it's for

Builders who want to embed Claude Code workflows into Ruby scripts, apps, or Rails projects.

What it delivers

You can build agent-driven Ruby workflows without leaving your app, while keeping control over tools, hooks, and sessions.

What it does

One-shot queries and live sessions

Use `query()` for a single exchange or `Client` for an open session with follow-up messages, interrupts, and streaming input.

In-process custom tools

Define tools as Ruby blocks, validate arguments with JSON Schema, and expose them to Claude through SDK MCP servers.

Hooks and permission callbacks

Run Ruby code at Claude lifecycle events like `PreToolUse` and decide programmatically whether a tool call may continue.

Rails support

Includes fiber-safe dispatch, initializer-style configuration, ActionCable streaming, and background-job session resumption.

CLI installer

Can vendor a pinned Claude Code binary into the project so production does not depend on a global install.

Observability and transports

Adds OpenTelemetry and Langfuse support, plus pluggable transports for containers, SSH, or remote runtimes.

Claude Code plugin bundle

Ships a plugin marketplace package and skill so Claude Code can learn the gem's APIs and patterns.

How to get it

  1. 1This repository is also a Claude Code plugin marketplace. The bundled skill teaches…
    /plugin marketplace add ya-luotao/claude-agent-sdk-ruby
    /plugin install claude-agent-ruby@claude-agent-sdk-ruby
  2. 2Run
    bundle install
    bundle exec rspec                    # unit suite
    bundle exec rubocop                  # lint
    RUN_INTEGRATION=1 bundle exec rspec  # also run the real-CLI integration suite (needs `claude` and ANTHROPIC_API_KEY)

README

Claude Agent SDK for Ruby

Gem Version CI Ruby Docs License: MIT

A Ruby SDK for the Claude Code agent runtime. Build AI agents, automate coding workflows, and integrate Claude into Rails and other Ruby applications with the same capabilities as the official TypeScript and Python SDKs.

Unofficial and community-maintained. This project is not affiliated with or supported by Anthropic. It tracks the official SDKs release by release; see the CHANGELOG for the currently synced version.

Highlights

  • Same wire protocol as the official SDKs. Spawns the claude CLI as a subprocess and speaks stream-JSON over stdin/stdout, so every feature of the runtime is available: sessions, subagents, sandboxing, structured output, file checkpointing and rewind.
  • query() for one-shot calls, Client for bidirectional sessions with interrupts, mid-session model switching, and streaming input from any Enumerator.
  • In-process custom tools. Define tools as Ruby blocks; they run inside your process with direct access to your app state (SDK MCP servers), with JSON-Schema-validated arguments.
  • All 27 hook events and permission callbacks with typed inputs, so you can gate, audit, or rewrite every tool call.
  • Rails-ready. Fiber-safe callback dispatch, an initializer-style configure block, ActionCable streaming, background-job session resumption, and a callback_scheduling: :inline mode for fiber workers.
  • Built-in OpenTelemetry observer with Langfuse support; no third-party instrumentation library required.
  • Pluggable transport to run the CLI somewhere else (an E2B microVM, a container, over SSH).
  • Hermetic deploys. CLIInstaller vendors a checksum-verified, pinned CLI binary into your project so production never depends on a global npm install.

Installation

# Gemfile
gem 'claude-agent-sdk', '~> 0.31.0'

Then bundle install, or install directly with gem install claude-agent-sdk. To track unreleased changes, point the Gemfile at GitHub: gem 'claude-agent-sdk', github: 'ya-luotao/claude-agent-sdk-ruby'.

Prerequisites

  • Ruby 3.2 or newer
  • Claude Code CLI 2.0.0 or newer, either installed globally (npm install -g @anthropic-ai/claude-code) or vendored with CLIInstaller:
# bin/setup or a cached Docker layer — pin a concrete version in production
ClaudeAgentSDK::CLIInstaller.install(version: '2.1.220')  # => "/app/vendor/claude/claude"

The vendored binary is found ahead of PATH, installs are idempotent and concurrency-safe, and a failed upgrade never breaks a working install. See docs/cli-installer.md for the full behaviour, supported platforms, and the CLI discovery order.

Quick Start

require 'claude_agent_sdk'

ClaudeAgentSDK.query(prompt: "What is 2 + 2?") do |message|
  puts message.text if message.is_a?(ClaudeAgentSDK::AssistantMessage)
end

query() — one-shot and streaming

query() runs a single conversation and yields each response message to the block.

options = ClaudeAgentSDK::ClaudeAgentOptions.new(
  system_prompt: "You are a helpful assistant",
  allowed_tools: ['Read', 'Write', 'Bash'],
  permission_mode: 'acceptEdits',
  cwd: "/path/to/project",
  max_turns: 5
)

ClaudeAgentSDK.query(prompt: "Create a hello.rb file", options: options) do |message|
  puts message
end

Pass an Enumerator instead of a string to stream several user messages into one session:

stream = ClaudeAgentSDK::Streaming.from_array(['Hello!', 'What is 2+2?', 'Thanks!'])

ClaudeAgentSDK.query(prompt: stream) do |message|
  puts message if message.is_a?(ClaudeAgentSDK::AssistantMessage)
end

Client — bidirectional sessions

Client keeps a session open so you can send follow-up queries, interrupt, switch models, and use hooks, permission callbacks, and custom tools. It runs inside an async block; blocking calls yield automatically, no await needed.

require 'claude_agent_sdk'
require 'async'

Async do
  client = ClaudeAgentSDK::Client.new

  begin
    client.connect
    client.query("What is the capital of France?")
    client.receive_response { |msg| puts msg }
  ensure
    client.disconnect
  end
end.wait

See docs/client.md for interrupt, mid-session model and permission switching, MCP status, and custom transports.

Custom tools (SDK MCP servers)

Tools are Ruby blocks that run in-process, with no subprocess or IPC between Claude's tool call and your code.

greet = ClaudeAgentSDK.create_tool('greet', 'Greet a user', { name: :string }) do |args|
  { content: [{ type: 'text', text: "Hello, #{args[:name]}!" }] }
end

server = ClaudeAgentSDK.create_sdk_mcp_server(name: 'my-tools', tools: [greet])

options = ClaudeAgentSDK::ClaudeAgentOptions.new(
  mcp_servers: { tools: server },
  allowed_tools: ['mcp__tools__greet']
)

Arguments are validated against the tool's JSON Schema before your handler runs, and handler exceptions are reported back to the model in-band so it can self-correct. See docs/mcp-servers.md for resources, prompts, mixed SDK + external servers, and schema details.

Hooks and permission callbacks

Hooks run your Ruby code at any of the 27 lifecycle events (PreToolUse, PostToolUse, UserPromptSubmit, Stop, PreCompact, …) with typed inputs. Permission callbacks decide programmatically whether a tool call may proceed.

options = ClaudeAgentSDK::ClaudeAgentOptions.new(
  hooks: { 'PreToolUse' => [ClaudeAgentSDK::HookMatcher.new(matcher: 'Bash', hooks: [my_hook])] },
  can_use_tool: my_permission_callback
)

See docs/hooks-and-permissions.md for the full event list and worked examples.

Documentation

TopicGuide
Client advanced features and custom transportsdocs/client.md
SDK MCP servers: tools, resources, prompts, schema compatibilitydocs/mcp-servers.md
All hook events, typed inputs, permission callbacksdocs/hooks-and-permissions.md
Structured output, thinking, budget, fallback and advisor models, sandbox, bare mode, checkpointingdocs/configuration.md
Session listing, reading, renaming, tagging, forking, resume-at-messagedocs/sessions.md
OpenTelemetry tracing, Langfuse, custom observersdocs/observability.md
Rails: fiber safety, solid_queue fiber workers, ActionCable, jobs, initializerdocs/rails.md
Vendoring a pinned CLI binary and CLI discovery orderdocs/cli-installer.md
Message, content block, and configuration type referencedocs/types.md
Error handling, exception hierarchy, timeoutsdocs/errors.md

API reference: rubydoc.info/gems/claude-agent-sdk. Available built-in tools: Claude Code documentation.

Examples

Runnable scripts live in examples/.

AreaExamples
Getting startedquick_start · client · streaming_input · message_types · error_handling
Sessions and outputsession_resumption · structured_output · extended_thinking · session_stores/
Tools and MCPmcp_calculator · mcp_resources_prompts · http_mcp_server
Hooks and permissionshooks · advanced_hooks · lifecycle_hooks · permission_callback
Models and limitsbudget_control · fallback_model · advisor · bare_mode · sandbox
Rails, observability, transportsrails_actioncable · rails_background_job · otel_langfuse · e2b_transport

Comparison with the official SDKs

All three SDKs drive the same CLI over the same protocol, so capabilities line up feature for feature. Ruby differs mainly in idiom: Enumerator for streaming input, blocks for tools, and the async gem with fibers instead of async/await.

CapabilityTypeScriptPythonRuby (this gem)
One-shot query()
Bidirectional Client
Streaming inputAsyncIterableAsyncIterableEnumerator
Custom tools (SDK MCP servers)tool()@tool decoratorcreate_tool block
Hooks (all 27 events)
Permission callbacks
Structured output
All 25 message typespartial
Sandbox settingspartial
Bare mode (--bare)
File checkpointing & rewind
Session browsing & mutations
Programmatic subagents
CLI binarybundledbundledvendored on demand (CLIInstaller)
Observability (OTel / Langfuse)via Arize✅ built-in
Custom transport (pluggable I/O)
Rails integration

Types are plain Ruby classes with attr_accessor and keyword arguments, mirroring the field names of the TypeScript Zod schemas and Python dataclasses; there is no runtime type checking.

Claude Code plugin

This repository is also a Claude Code plugin marketplace. The bundled skill teaches Claude Code the gem's APIs and patterns:

/plugin marketplace add ya-luotao/claude-agent-sdk-ruby
/plugin install claude-agent-ruby@claude-agent-sdk-ruby

Development

bundle install
bundle exec rspec                    # unit suite
bundle exec rubocop                  # lint
RUN_INTEGRATION=1 bundle exec rspec  # also run the real-CLI integration suite (needs `claude` and ANTHROPIC_API_KEY)

CI runs the suite and RuboCop on Ruby 3.2, 3.3, and 3.4. See spec/README.md for the test layout.

Contributing

Bug reports and pull requests are welcome on GitHub. Please include a failing spec with bug reports where possible, and keep pull requests focused on one change. Releases follow Semantic Versioning and are recorded in the CHANGELOG.

License

Released under the MIT License.

Files in the repo

Repository payload25 top-level entries
  • .claude
  • .claude-plugin
  • .github
  • assets
  • docs
  • examples
  • lib
  • plugins
  • skills
  • spec
  • .gitignore
  • .rspec
  • .rubocop_todo.yml
  • .rubocop.yml
  • .yardopts
  • AUDIT-2026-06-12.md
  • AUDIT-2026-07-03.md
  • CHANGELOG.md
  • claude-agent-sdk.gemspec
  • CLAUDE.md
  • Gemfile
  • IMPLEMENTATION.md
  • LICENSE
  • Rakefile
  • README.md

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More frameworks & sdks

HKUDS/nanobotFrameworks & SDKs

Ultra-lightweight, open-source, self-hosted personal AI agent framework in Python with WebUI, tools, memory, MCP, multi-agent workflows, automation, and chat apps

48k
microsoft/
SkillOpt
microsoft/SkillOptFrameworks & SDKs

SkillOpt is a text-space optimizer that trains reusable natural-language skills for frozen LLM agents through trajectory-driven edits, validation-gated updates, and deployable best_skill.md artifacts.

17k
omnigent-ai/omnigentFrameworks & SDKs

Omnigent is an open-source AI agent framework and meta-harness: orchestrate Claude Code, Codex, Cursor, Pi, and custom agents — swap harnesses without rewriting, enforce policies and sandboxing, and collaborate in real time from any device.

9.8k
kyegomez/
OpenMythos
kyegomez/OpenMythosFrameworks & SDKs

A theoretical reconstruction of the Claude Mythos architecture, built from first principles using the available research literature.

15k
D4Vinci/ScraplingFrameworks & SDKs

🕷️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!

80k