anthropic-sdk-ruby
CLAUDE.md370 starsChanged 2 months agoMITView on GitHub
Context for contributors on how this SDK is put together, plus the things reviews most often come back to. Setup instructions live in CONTRIBUTING.md.
- Reads credentials
The file
We split this CLAUDE.md into the rules it gives an agent
2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 59
Not every block streams as text-style appends: some arrive complete at content_block_start, others as a placeholder plus one delta …
- Distinctive: line 62
Unverified claims about the API: Check doc comments, error messages and PR text that say "the API rejects X" or "model Y requires Z" …
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Working in this repository
Context for contributors on how this SDK is put together, plus the things reviews most often come back to. Setup instructions live in CONTRIBUTING.md.
Overview
- The official Ruby SDK for the Claude API (the
anthropicgem). Much of it is produced via code generation from the OpenAPI spec, with hand-written helpers (lib/anthropic/helpers/**: streaming, tools, input schemas, platform clients), credentials, middleware and examples layered on top. - Generated files are safe to edit. New generator output is git-merged with custom changes rather than overwriting them, so fix things where they live; a collision is just a merge conflict.
- Fix things upstream first wherever you can, before reaching for custom code: a missing parameter, an out-of-date doc string, or a response the models can't represent (a missing required field, an unknown enum member, a nullability mismatch) belongs in the OpenAPI spec, and broken generated infrastructure (
lib/anthropic/internal/**: transport, retries, SSE and multipart handling, coercion) belongs in the generator — fixing it there is preferred over a local patch. - PRs target the default branch (
mainon the public repo).nextbelongs to release automation — don't open PRs against it or push to it; a commit that lands there outside the release flow breaks the sync. Rebase onto the current default branch before asking for review — a stale base shows up as unrelated "changed" files. lib/anthropic/version.rb,.release-please-manifest.json, the gem's own entry inGemfile.lock, theREADME.mdversion block andCHANGELOG.mdare written by release automation.
Build, test, lint
./scripts/bootstrapinstalls the bundle;./scripts/teststarts the mock API server (./scripts/mock, needs Node) and runs the suite; run./scripts/lintbefore pushing (it is exactly what CI runs) and format only the files you touched, e.g.bundle exec rubocop -a <files>— a whole-tree./scripts/formatalso reflows long lines and restylesrbi//sig/files you never opened, since CI doesn't check formatting. A single file runs withbundle exec rake test TEST=test/anthropic/…_test.rb.- Lint is rubocop plus
steep check(RBS) plus Sorbet, and the Sorbet step issrb typecheck --dir examples— the examples are type-checked in CI on top ofrbi/. A barebundle exec srb tcnever looks atexamples/, which is how "green locally, red in CI" has happened; use the--dir examplesform after touching examples or any signature they use. Rubocop runs withLayout/LineLengthexcluded, so line length is never what fails CI; trailing whitespace (easy to pick up while resolving a sync conflict) and missing parentheses are. - Only the generated
ResourceTestsuites undertest/anthropic/resources/**need the mock server (port 4010, orTEST_API_BASE_URL);APIConnectionErrors there mean the mock isn't running. Everything else runs offline against WebMock — helper, credentials, middleware and client tests, plus the hand-writtenresources/messages/streaming_test.rbandresources/beta/messages/streaming_test.rbthat sit inside that directory. Live tests against real cloud providers only run withANTHROPIC_LIVE=1, and the Bedrock/AWS unit tests read ambient AWS state (AWS_*variables and~/.awsprofiles), so if they fail locally on region, profile or credential lookup, run them withAWS_*unset andAWS_CONFIG_FILE=/dev/null AWS_SHARED_CREDENTIALS_FILE=/dev/null. - CI's
./scripts/detect-breaking-changesrestores the release base's generated tests andclient_test.rband re-runs./scripts/lintover them, but nothing in lint type-checkstest/, so it will not notice a removed or renamed method or keyword — treat public-surface removals as a review item: deprecate first (a forwarding alias pluswarn(…, category: :deprecated)) and remove later, in step with the other SDKs. - The gem supports Ruby 3.2+, and users also run it on Ruby 4 (Prism) and JRuby, which CI doesn't cover; both have broken on load-time edge cases before (bytecode precompilation of unusual syntax, constant resolution during
require), so keep load-time code boring and take reports from those runtimes seriously. - Examples are executable scripts (
#!/usr/bin/env ruby,# frozen_string_literal: true, a# typed:sigil,require_relative "../lib/anthropic"), linted and type-checked with everything else. Match the sigil of neighbouring examples of the same kind: client and streaming examples aretyped: strong, while theBaseModel/BaseToolDSL examples (tools, tool runner, structured output, input schemas) can't type-check today and staytyped: falseor unsigilled, where Sorbet checks little beyond syntax and constant names. New user-facing helpers usually come with an example and ahelpers.mdsection, using a current public model id like the neighbouring examples; user documentation beyondhelpers.mdlives outside this repo (see CONTRIBUTING.md), so say in the PR what needs documenting.
Types and signatures
- Generated code exists three times: Ruby with YARD docs in
lib/, Sorbet inrbi/, RBS insig/. Solargraph reads the YARD, Sorbet/Tapioca the.rbi, Steep and ruby-lsp the.rbs, and no tool compares either signature set withlib/(steep checkvalidatessig/on its own; Sorbet readsrbi/andexamples/), so agreement is kept by review — which regularly catches a keyword present inlib/but missing from a signature, or a documented block signature that doesn't match what the code yields..rbifiles repeat the YARD prose;.rbsfiles carry none. Not every hand-written helper has all three yet: update whichever surfaces exist for the thing you touch, and give new public helpers all three. - Sorbet has no literal types, so API enums are branded
Symbolaliases with constants (Anthropic::StopReason::TOOL_USE,Anthropic::Models::AnthropicBeta::*). In Sorbet-checked files — the typed examples —message.stop_reason == :tool_useis an error (an always-false comparison) and Sorbet never narrows throughcase … in, which it rejects outright as an untyped branch undertyped: strong; narrow withcase … when Klass,content.grep(Anthropic::Models::ToolUseBlock)oris_a?, or compare against the constants. - Public value objects are plain classes with explicit readers declared in all three surfaces (
Anthropic::APIRequest/APIResponse) rather thanData.define/Struct, whose synthesized members LSPs and both checkers can't see. - Sorbet upgrades have turned previously valid
.rbioutput into errors for downstream Tapioca users before; if the lockfile'ssorbetmoves, run the fullrake typecheckand fixrbi/in the same PR.
Code organization
Anthropic::Helpers::*holds the hand-written features, and the short public names are alias shims at the top oflib/anthropic/(streaming.rb→Anthropic::Streaming,bedrock.rb→Anthropic::BedrockClient,vertex.rb,aws.rb,bedrock_mantle.rb,google_cloud.rb,input_schema.rb,mcp.rb). A new public helper gets a shim, its rbi/rbs, and ahelpers.mdmention.lib/anthropic.rbis one explicitrequire_relativelist — there is no autoload, and usersrequire "anthropic"themselves — so new files go there in dependency order (and a newly used stdlib intomanifest.yaml; the Steepfile loads each entry as an RBS library, so a stdlib without RBS signatures also goes in its exclusion list orsteep checkfails). When a codegen sync conflicts in that file, keep every hand-writtenrequire_relativeand take the generated side as it is — its removals as well as its additions — then check thatbundle exec ruby -e 'require "./lib/anthropic"'still loads.- The runtime tier (
lib/anthropic/internal/**) stays provider-agnostic and dependency-free: the gem ships its own Net::HTTP transport, multipart writer and SSE decoder so it can stream in both directions without pinning an HTTP stack on applications. Runtime dependencies are the four range-pinned gems in the gemspec (exercised across versions bydependency-versions.yml); optional integrations (aws-sdk-bedrockruntime/aws-sdk-core,googleauth,mcp) are required lazily inside the helper that needs them, with an error naming the gem to add; and provider-specific decoding such as Bedrock's binary event-stream lives inhelpers/bedrock/, applied from that client'sprovider_middleware. - A lot of logic exists twice, GA and beta (
resources/messages.rb/resources/beta/messages.rb, theModels::X | Models::BetaXarms inMessageStream, the GA and betaresources/**/streaming_test.rbsuites), some entry points come in fours (create/stream/stream_raw/count_tokens), and the platform clients (helpers/{bedrock,aws,vertex,google_cloud}/plusbedrock/mantle_client.rb) each derive their own base URL and attach per-attempt auth, with Bedrock and Vertex also rewriting the request inadapt_request. A fix usually needs applying to every twin — a streaming-header fix once landed in the generatedstream_rawand missed the hand-writtenstreambeside it — and a shared piece (Helpers::Messages,AWSAuth) beats parallel copies. - For anything cross-SDK (environment variable and option names, header semantics, credential precedence, the non-streaming
max_tokens/timeout guard, telemetry values, helper shapes such as the accumulated stream returning the non-streamingMessage), matching the other SDKs is the default; mention a deliberate divergence in the PR.
Errors
- Everything the SDK raises on its own behalf derives from
Anthropic::Errors::Error(lib/anthropic/errors.rb), so callers can rescue the family in one clause:APIStatusError— the service answered with an error; carriesurl,status,headers,bodyand the parsedtype(the body'serror.type), andAPIStatusError.forpicks the concrete subclass by status (BadRequestError,AuthenticationError,PermissionDeniedError,NotFoundError,ConflictError,UnprocessableEntityError,RateLimitError,InternalServerError, otherwise plainAPIStatusError). It is raised only once the retry policy is done (408/409/429/5xx, or whateverx-should-retrysays, are retried first), and anerrorevent inside an otherwise successful stream goes through the same factory off the already-open response, sotypesays more thanstatusthere.APIConnectionError, withAPITimeoutErrorbeneath it — a transport failure with no status, which the client counts as retryable; it shares theAPIErrorparent (url/status/headers/body) withAPIStatusError.ConversionError— a typed reader whose value didn't fit the model; the message points atModel[:field]for the raw value andcausecarries the underlying error.RetryableError— what middleware raises, or wraps anywhere in thecausechain, to opt a failure into the retry loop.ConfigurationErrorfor the credentials/config layer, and feature-specific subclasses next to their feature where a family of failures deserves its own type (Credentials::WorkloadIdentityError,APIResponse::ConsumedBodyError, the session accumulator'sAccumulationError).
- Deliberately outside that family: bad arguments or option combinations at public entry points raise
ArgumentError; a resource a platform client can't offer raisesNotImplementedError; a missing optional gem raises aRuntimeError/LoadErrornaming the gem to install; and an exception from a tool inside the tool runner isn't an SDK failure — it becomes anis_error: truetool_resultfor the model. - New code reuses these rather than adding types or raising bare
StandardError/RuntimeErrorfor SDK conditions, keeps the original exception ascause, and leaves HTTP-status mapping toAPIStatusError.for.
Common mistakes
- Rewriting or second-guessing the request. Don't validate, hoist, merge, reorder or drop parts of a request the caller built. Transform input only as far as the API spec specifies and pass the rest through verbatim (
extra_body/extra_headers/extra_queryexist so power users can always send what they need), letting the API return an actionable 400. (Protocol translation inadapt_request—modelinto the URL,anthropic_version/anthropic_betainto the body — is mapping, not rewriting.) - Inferring capabilities from model IDs. Model-name lists go stale on the next launch and rarely cover the Bedrock/Vertex spellings; use an explicit option or just send the request. (The exact-match tables mirrored from the other SDKs —
Client::MODEL_NONSTREAMING_TOKENSandResources::Messages::MODELS_TO_WARN_WITH_THINKING_ENABLED— are the accepted precedents.) - Raising on data the SDK doesn't recognize. Responses can carry enum values, block types and fields this version doesn't model, and the converters never raise on them: an unknown enum member comes through as the raw String, an unknown
typeinside a union of models is coerced best-effort into the nearest known variant class (whose#typeis then that raw String, unknown fields still reachable through#to_h), and only wholly unmatched values stay Hashes — so a class match can receive unknown data, and code that cares checkstypeor the generated constants. Hand-written code should degrade the same way: handle what you recognize and pass the rest through — especially inMessageStream, the tool runner and middleware, where an exception tears down the caller's response — keeping fallback arms as no-ops unless the stream is genuinely malformed. - Losing wire data on the way back to the API. When relaying API output into a new request, carry the model or a copy of its raw hash across (
to_his the model's live storage, sodupbefore changing it) rather than rebuilding from typed readers, which raiseConversionErrorfor values that failed coercion (model[:key]still holds the raw value). Request bodies are symbol-keyed, so normalize a user hash's string keys once at the boundary (a stray"model"string key once duplicated the field on the wire); wire names come fromConverter.dump(format, notformat_); andTimegoes out as RFC 3339 (iso8601), neverto_s. - Sending
nilwhere the key should be omitted.BaseModel#to_hand request hashes keep a key if it was ever set, so an explicitly assignednilserializes asnull, which the API treats differently from an omitted key — build hashes without the keys you don't mean to send, and apply overrides delete-on-nil rather than withHash#merge. - Streaming assumptions that don't hold (each has bitten the accumulator at least once):
- The accumulated message has to equal the non-streaming
Message, GA and beta, so every field ofRawMessageDeltaEvent/MessageDeltaUsageand theirBetatwins gets folded, and bothresources/**/streaming_test.rbsuites test it. - Assigning
nilthrough a generated setter poisons the field — even one declarednil?: true— so the next typed read raises; copy delta fields only when present. - An arm naming
Models::Xbut notModels::BetaXsilently no-ops on beta streams. - Not every block streams as text-style appends: some arrive complete at
content_block_start, others as a placeholder plus one delta (compaction).
- The accumulated message has to equal the non-streaming
- Clobbering headers.
Util.normalized_headersis last-wins by design (signed headers, a multipartcontent-typeand a caller'sx-api-keyall rely on replacing), withanthropic-betaas the one comma-joined exception; beta flags arrive from thebetas:param, generator-injected per-endpoint defaults and OAuth, and all of them have to survive (in hand-written code the generatedAnthropicBeta::*constants age better than date literals). The helper-telemetry header is likewise a set — append and de-duplicate through the existing merge helper rather than overwriting it. Header names compare case-insensitively internally, butNet::HTTPre-canonicalizes their casing on the wire. - Transport slips. SigV4 clients sign every attempt over the exact bytes sent (materialize enumerable/multipart bodies first;
encode_contentpasses an already-encoded body through) — reusing a signature across retries has shipped twice as 403s. A body containing anIOmakes the request non-retryable on purpose (can_retry), since pipes can't be rewound. Streaming requests sendaccept-encoding: identity, or every event arrives in one burst at the end. LeavingNet::HTTP#read_bodyearly takesthrow/catch, notbreak. Middleware runs per attempt inside the retry loop, receives an immutableAPIRequestand anAPIResponsefor every status, and opts into retries withErrors::RetryableError. - Unverified claims about the API. Check doc comments, error messages and PR text that say "the API rejects X" or "model Y requires Z" against the official Claude API docs, not a third-party page or a bug report.
Style notes
- Type safety comes first. Downgrading a
# typed:sigil, widening a signature toT.anything/untyped, or comparing enum values as bare strings is occasionally necessary but usually a sign to restructure — narrow by class, keep@param/@returnand rbi/rbs types precise, and let the converters do coercion.T.*helpers are forrbi/only: the gem doesn't loadsorbet-runtime, soT.must/T.cast/T.let/T.unsafeinlib/,examples/ortest/type-check fine and then raiseNameErrorwhen the code runs. - Immutable things should actually be immutable: freeze constants and lookup tables, deep-freeze what you hand to user code (
Util.deep_frozen_copy, as the middleware path does forAPIRequest),dupcaller-supplied arrays and hashes before storing them, and don't hand out references that let callers mutate state presented as fixed. - Rubocop settles most formatting; the recurring manual points are double quotes unless the string contains them (
'{"a": 1}'beats escapes, in YARD examples too), parentheses on calls with arguments inside methods and blocks,alias_method, bracketed symbol arrays,_1/_2block params, and fencing a deliberateType === valuewithrubocop:disable Style/CaseEqualityrather than letting autocorrect turn it intois_a?. Pattern matching is the house idiom inlib/andtest/, which Sorbet doesn't read; typed examples usecase … when. - New siblings follow the existing shape: hash-or-model reads go through
Runner#read_field, tool serialization and API names throughHelpers::Messages.distill_input_schema_models!/tool_api_name, structured-output parsing through theunwrapstep (parse_input_schemas!) that any new response path has to thread through, optional gems through the lazyrequirein the Vertex client. "How do we already do this elsewhere?" is usually the first review question, and new public surface (aBaseToolDSL keyword, a constructor option, an env-var name) is a maintainer call rather than something to slip into a fix. - Comments and YARD in moderation: worth writing for the non-obvious (an invariant, a wire-format reason, the admission rule for a lookup table), not to restate what the code does or narrate its history — over-documenting the obvious is its own review finding. Param docs read "Defaults to
ENV["…"], otherwise …" and skip internal mechanics; product names in prose follow the public docs, while identifiers, env vars and error strings never change for a rebrand.
Tests
- A behaviour change comes with a test that fails before and passes after (worth saying so in the PR), covering the beta twin when the code is shared. Watch for vacuous cases — a lookup table was once mostly deleted under a "covering" test that stayed green because its inputs took a default path — and remember
assert_pattern { actual => ^expected }compares whileactual => expectedmerely binds. test_helper.rbturns onparallelize_me!andprove_it!, so every test asserts something and classes run in parallel unless theyextend Minitest::Serial— which hand-written classes touchingENV, WebMock or other process state do, alongsideinclude WebMock::APIwithenable!/disable!inbefore_all/after_allandreset!inteardown. Restore anyENVyou change; the fewi_suck_and_my_tests_are_order_dependent!classes are debt, not precedent.- Retry paths don't really sleep in tests:
Kernel#sleep/Time.nowhonour the:mock_sleep/:time_nowthread variables, so setThread.current.thread_variable_set(:mock_sleep, [])insetupwhen a test can retry. - For request-shaping code, asserting on the exact wire request is what makes the test meaningful — WebMock's
assert_requested(…) { |req| … }paired with a realassert_*(plainwebmockis loaded, soassert_requestedalone doesn't count towardsprove_it!), or a capturingrequest_options: {middleware: ->(req, nxt) { … }}; for streaming, serve literal SSE bytes and checkaccumulated_message. Generated resource tests only check shapes against the mock, so behaviour tests for patches inresources/*go in hand-written files such astest/anthropic/resources/messages/streaming_test.rband itsbeta/twin.
Commits and pull requests
- Conventional Commits drive release-please and the changelog (
feat(scope):,fix(scope):,chore,docs;testandciare hidden). A!orBREAKING CHANGE:footer cuts a major version, which is rare and a maintainer call — describe the compatibility impact in the PR instead. - One logical change per PR, against the current default branch, with formatting-only churn in its own commit.
- A good PR description says what was wrong (a short before/after helps), what changed, and what gives confidence — the failing-then-passing test plus any manual verification, and what the sibling SDKs do when the change is visible on the wire — and calls out behaviour changes and anything left unverified (no mock server, no cloud credentials) rather than implying it passed.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

