
Claude Api
- 6 installs
- 15 repo stars
- Updated August 1, 2026
- connorads/dotfiles
This is a copy of claude-api by anthropics - installs and ranking accrue to the original listing.
Helps with backend & apis tasks.
About
claude-api is a Claude Code skill for backend & apis. It helps solo builders move faster with AI-assisted development.
- claude-api
- Backend & APIs
- AI-coding skill
Claude Api by the numbers
- 6 all-time installs (skills.sh)
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/connorads/dotfiles --skill claude-apiAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 6 |
|---|---|
| repo stars | ★ 15 |
| Last updated | August 1, 2026 |
| Repository | connorads/dotfiles ↗ |
What it does
Helps with backend & apis tasks.
Files
Building LLM-Powered Applications with Claude
This skill helps you build LLM-powered applications with Claude. Choose the right surface based on your needs, detect the project language, then read the relevant language-specific documentation.
Before You Start
Scan the target file (or, if no target file, the prompt and project) for non-Anthropic provider markers — import openai, from openai, langchain_openai, OpenAI(, gpt-4, gpt-5, file names like agent-openai.py or *-generic.py, or any explicit instruction to keep the code provider-neutral. If you find any, stop and tell the user that this skill produces Claude/Anthropic SDK code; ask whether they want to switch the file to Claude or want a non-Claude implementation. Do not edit a non-Anthropic file with Anthropic SDK calls.
Output Requirement
When the user asks you to add, modify, or implement a Claude feature, your code must call Claude through one of:
1. The official Anthropic SDK for the project's language (anthropic, @anthropic-ai/sdk, com.anthropic.*, etc.). This is the default whenever a supported SDK exists for the project. 2. Raw HTTP (curl, requests, fetch, httpx, etc.) — only when the user explicitly asks for cURL/REST/raw HTTP, the project is a shell/cURL project, or the language has no official SDK.
Never mix the two — don't reach for requests/fetch in a Python or TypeScript project just because it feels lighter. Never fall back to OpenAI-compatible shims.
Never guess SDK usage. Function names, class names, namespaces, method signatures, and import paths must come from explicit documentation — either the {lang}/ files in this skill or the official SDK repositories or documentation links listed in shared/live-sources.md. If the binding you need is not explicitly documented in the skill files, WebFetch the relevant SDK repo from shared/live-sources.md before writing code. Do not infer Ruby/Java/Go/PHP/C# APIs from cURL shapes or from another language's SDK.
Defaults
Unless the user requests otherwise:
For the Claude model version, please use Claude Opus 4.7, which you can access via the exact model string claude-opus-4-7. Please default to using adaptive thinking (thinking: {type: "adaptive"}) for anything remotely complicated. And finally, please default to streaming for any request that may involve long input, long output, or high max_tokens — it prevents hitting request timeouts. Use the SDK's .get_final_message() / .finalMessage() helper to get the complete response if you don't need to handle individual stream events
---
Subcommands
If the User Request at the bottom of this prompt is a bare subcommand string (no prose), search every Subcommands table in this document — including any in sections appended below — and follow the matching Action column directly. This lets users invoke specific flows via /claude-api <subcommand>. If no table in the document matches, treat the request as normal prose.
---
Language Detection
Before reading code examples, determine which language the user is working in:
1. Look at project files to infer the language:
*.py,requirements.txt,pyproject.toml,setup.py,Pipfile→ Python — read frompython/*.ts,*.tsx,package.json,tsconfig.json→ TypeScript — read fromtypescript/*.js,*.jsx(no.tsfiles present) → TypeScript — JS uses the same SDK, read fromtypescript/*.java,pom.xml,build.gradle→ Java — read fromjava/*.kt,*.kts,build.gradle.kts→ Java — Kotlin uses the Java SDK, read fromjava/*.scala,build.sbt→ Java — Scala uses the Java SDK, read fromjava/*.go,go.mod→ Go — read fromgo/*.rb,Gemfile→ Ruby — read fromruby/*.cs,*.csproj→ C# — read fromcsharp/*.php,composer.json→ PHP — read fromphp/
2. If multiple languages detected (e.g., both Python and TypeScript files):
- Check which language the user's current file or question relates to
- If still ambiguous, ask: "I detected both Python and TypeScript files. Which language are you using for the Claude API integration?"
3. If language can't be inferred (empty project, no source files, or unsupported language):
- Use AskUserQuestion with options: Python, TypeScript, Java, Go, Ruby, cURL/raw HTTP, C#, PHP
- If AskUserQuestion is unavailable, default to Python examples and note: "Showing Python examples. Let me know if you need a different language."
4. If unsupported language detected (Rust, Swift, C++, Elixir, etc.):
- Suggest cURL/raw HTTP examples from
curl/and note that community SDKs may exist - Offer to show Python or TypeScript examples as reference implementations
5. If user needs cURL/raw HTTP examples, read from curl/.
Language-Specific Feature Support
| Language | Tool Runner | Managed Agents | Notes |
|---|---|---|---|
| Python | Yes (beta) | Yes (beta) | Full support — @beta_tool decorator |
| TypeScript | Yes (beta) | Yes (beta) | Full support — betaZodTool + Zod |
| Java | Yes (beta) | Yes (beta) | Beta tool use with annotated classes |
| Go | Yes (beta) | Yes (beta) | BetaToolRunner in toolrunner pkg |
| Ruby | Yes (beta) | Yes (beta) | BaseTool + tool_runner in beta |
| C# | No | No | Official SDK |
| PHP | Yes (beta) | Yes (beta) | BetaRunnableTool + toolRunner() |
| cURL | N/A | Yes (beta) | Raw HTTP, no SDK features |
Managed Agents code examples: dedicated language-specific READMEs are provided for Python, TypeScript, Go, Ruby, PHP, Java, and cURL ({lang}/managed-agents/README.md,curl/managed-agents.md). Read your language's README plus the language-agnosticshared/managed-agents-*.mdconcept files. Agents are persistent — create once, reference by ID. Store the agent ID returned byagents.createand pass it to every subsequentsessions.create; do not callagents.createin the request path. The Anthropic CLI is one convenient way to create agents and environments from version-controlled YAML — its URL is inshared/live-sources.md. If a binding you need isn't shown in the README, WebFetch the relevant entry fromshared/live-sources.mdrather than guess. C# does not currently have Managed Agents support; use cURL-style raw HTTP requests against the API.
---
Which Surface Should I Use?
Start simple. Default to the simplest tier that meets your needs. Single API calls and workflows handle most use cases — only reach for agents when the task genuinely requires open-ended, model-driven exploration.
| Use Case | Tier | Recommended Surface | Why |
|---|---|---|---|
| Classification, summarization, extraction, Q&A | Single LLM call | Claude API | One request, one response |
| Batch processing or embeddings | Single LLM call | Claude API | Specialized endpoints |
| Multi-step pipelines with code-controlled logic | Workflow | Claude API + tool use | You orchestrate the loop |
| Custom agent with your own tools | Agent | Claude API + tool use | Maximum flexibility |
| Server-managed stateful agent with workspace | Agent | Managed Agents | Anthropic runs the loop and hosts the tool-execution sandbox |
| Persisted, versioned agent configs | Agent | Managed Agents | Agents are stored objects; sessions pin to a version |
| Long-running multi-turn agent with file mounts | Agent | Managed Agents | Per-session containers, SSE event stream, Skills + MCP |
Note: Managed Agents is the right choice when you want Anthropic to run the agent loop and host the container where tools execute — file ops, bash, code execution all run in the per-session workspace. If you want to host the compute yourself or run your own custom tool runtime, Claude API + tool use is the right choice — use the tool runner for automatic loop handling, or the manual loop for fine-grained control (approval gates, custom logging, conditional execution).
Third-party providers (Amazon Bedrock, Google Vertex AI, Microsoft Foundry): Managed Agents is not available on Bedrock, Vertex, or Foundry. If you are deploying through any third-party provider, use Claude API + tool use for all use cases — including ones where Managed Agents would otherwise be the recommended surface.
Decision Tree
What does your application need?
0. Are you deploying through Amazon Bedrock, Google Vertex AI, or Microsoft Foundry?
└── Yes → Claude API (+ tool use for agents) — Managed Agents is 1P only.
No → continue.
1. Single LLM call (classification, summarization, extraction, Q&A)
└── Claude API — one request, one response
2. Do you want Anthropic to run the agent loop and host a per-session
container where Claude executes tools (bash, file ops, code)?
└── Yes → Managed Agents — server-managed sessions, persisted agent configs,
SSE event stream, Skills + MCP, file mounts.
Examples: "stateful coding agent with a workspace per task",
"long-running research agent that streams events to a UI",
"agent with persisted, versioned config used across many sessions"
3. Workflow (multi-step, code-orchestrated, with your own tools)
└── Claude API with tool use — you control the loop
4. Open-ended agent (model decides its own trajectory, your own tools, you host the compute)
└── Claude API agentic loop (maximum flexibility)Should I Build an Agent?
Before choosing the agent tier, check all four criteria:
- Complexity — Is the task multi-step and hard to fully specify in advance? (e.g., "turn this design doc into a PR" vs. "extract the title from this PDF")
- Value — Does the outcome justify higher cost and latency?
- Viability — Is Claude capable at this task type?
- Cost of error — Can errors be caught and recovered from? (tests, review, rollback)
If the answer is "no" to any of these, stay at a simpler tier (single call or workflow).
---
Architecture
Everything goes through POST /v1/messages. Tools and output constraints are features of this single endpoint — not separate APIs.
User-defined tools — You define tools (via decorators, Zod schemas, or raw JSON), and the SDK's tool runner handles calling the API, executing your functions, and looping until Claude is done. For full control, you can write the loop manually.
Server-side tools — Anthropic-hosted tools that run on Anthropic's infrastructure. Code execution is fully server-side (declare it in tools, Claude runs code automatically). Computer use can be server-hosted or self-hosted.
Structured outputs — Constrains the Messages API response format (output_config.format) and/or tool parameter validation (strict: true). The recommended approach is client.messages.parse() which validates responses against your schema automatically. Note: the old output_format parameter is deprecated; use output_config: {format: {...}} on messages.create().
Supporting endpoints — Batches (POST /v1/messages/batches), Files (POST /v1/files), Token Counting, and Models (GET /v1/models, GET /v1/models/{id} — live capability/context-window discovery) feed into or support Messages API requests.
---
Current Models (cached: 2026-04-15)
| Model | Model ID | Context | Input $/1M | Output $/1M |
|---|---|---|---|---|
| Claude Opus 4.7 | claude-opus-4-7 | 1M | $5.00 | $25.00 |
| Claude Opus 4.6 | claude-opus-4-6 | 1M | $5.00 | $25.00 |
| Claude Sonnet 4.6 | claude-sonnet-4-6 | 1M | $3.00 | $15.00 |
| Claude Haiku 4.5 | claude-haiku-4-5 | 200K | $1.00 | $5.00 |
ALWAYS use `claude-opus-4-7` unless the user explicitly names a different model. This is non-negotiable. Do not use claude-sonnet-4-6, claude-sonnet-4-5, or any other model unless the user literally says "use sonnet" or "use haiku". Never downgrade for cost — that's the user's decision, not yours.
CRITICAL: Use only the exact model ID strings from the table above — they are complete as-is. Do not append date suffixes. For example, use claude-sonnet-4-5, never claude-sonnet-4-5-20250514 or any other date-suffixed variant you might recall from training data. If the user requests an older model not in the table (e.g., "opus 4.5", "sonnet 3.7"), read shared/models.md for the exact ID — do not construct one yourself.
A note: if any of the model strings above look unfamiliar to you, that's to be expected — that just means they were released after your training data cutoff. Rest assured they are real models; we wouldn't mess with you like that.
Live capability lookup: The table above is cached. When the user asks "what's the context window for X", "does X support vision/thinking/effort", or "which models support Y", query the Models API (client.models.retrieve(id) / client.models.list()) — see shared/models.md for the field reference and capability-filter examples.
---
Thinking & Effort (Quick Reference)
Opus 4.7 — Adaptive thinking only: Use thinking: {type: "adaptive"}. thinking: {type: "enabled", budget_tokens: N} returns a 400 on Opus 4.7 — adaptive is the only on-mode. {type: "disabled"} and omitting thinking both work. Sampling parameters (temperature, top_p, top_k) are also removed and will 400. See shared/model-migration.md → Migrating to Opus 4.7 for the full breaking-change list. Opus 4.6 — Adaptive thinking (recommended): Use thinking: {type: "adaptive"}. Claude dynamically decides when and how much to think. No budget_tokens needed — budget_tokens is deprecated on Opus 4.6 and Sonnet 4.6 and should not be used for new code. Adaptive thinking also automatically enables interleaved thinking (no beta header needed). When the user asks for "extended thinking", a "thinking budget", or `budget_tokens`: always use Opus 4.7 or 4.6 with `thinking: {type: "adaptive"}`. The concept of a fixed token budget for thinking is deprecated — adaptive thinking replaces it. Do NOT use `budget_tokens` for new 4.6/4.7 code and do NOT switch to an older model. Gradual-migration carve-out: budget_tokens is still functional on Opus 4.6 and Sonnet 4.6 as a transitional escape hatch — if you're migrating existing code and need a hard token ceiling before you've tuned effort, see shared/model-migration.md → Transitional escape hatch. Note: this carve-out does not apply to Opus 4.7 — budget_tokens is fully removed there. Effort parameter (GA, no beta header): Controls thinking depth and overall token spend via output_config: {effort: "low"|"medium"|"high"|"max"} (inside output_config, not top-level). Default is high (equivalent to omitting it). max is Opus-tier only (Opus 4.6 and later — not Sonnet or Haiku). Opus 4.7 adds "xhigh" (between high and max) — the best setting for most coding and agentic use cases on 4.7, and the default in Claude Code; use a minimum of high for most intelligence-sensitive work. Works on Opus 4.5, Opus 4.6, Opus 4.7, and Sonnet 4.6. Will error on Sonnet 4.5 / Haiku 4.5. On Opus 4.7, effort matters more than on any prior Opus — re-tune it when migrating. Combine with adaptive thinking for the best cost-quality tradeoffs. Lower effort means fewer and more-consolidated tool calls, less preamble, and terser confirmations — high is often the sweet spot balancing quality and token efficiency; use max when correctness matters more than cost; use low for subagents or simple tasks.
Opus 4.7 — thinking content omitted by default: thinking blocks still stream but their text is empty unless you opt in with thinking: {type: "adaptive", display: "summarized"} (default is "omitted"). Silent change — no error. If you stream reasoning to users, the default looks like a long pause before output; set "summarized" to restore visible progress.
Task Budgets (beta, Opus 4.7): output_config: {task_budget: {type: "tokens", total: N}} tells the model how many tokens it has for a full agentic loop — it sees a running countdown and self-moderates (minimum 20,000; beta header task-budgets-2026-03-13). Distinct from max_tokens, which is an enforced per-response ceiling the model is not aware of. See shared/model-migration.md → Task Budgets.
Sonnet 4.6: Supports adaptive thinking (thinking: {type: "adaptive"}). budget_tokens is deprecated on Sonnet 4.6 — use adaptive thinking instead.
Older models (only if explicitly requested): If the user specifically asks for Sonnet 4.5 or another older model, use thinking: {type: "enabled", budget_tokens: N}. budget_tokens must be less than max_tokens (minimum 1024). Never choose an older model just because the user mentions budget_tokens — use Opus 4.7 with adaptive thinking instead.
---
Compaction (Quick Reference)
Beta, Opus 4.7, Opus 4.6, and Sonnet 4.6. For long-running conversations that may exceed the 1M context window, enable server-side compaction. The API automatically summarizes earlier context when it approaches the trigger threshold (default: 150K tokens). Requires beta header compact-2026-01-12.
Critical: Append response.content (not just the text) back to your messages on every turn. Compaction blocks in the response must be preserved — the API uses them to replace the compacted history on the next request. Extracting only the text string and appending that will silently lose the compaction state.
See {lang}/claude-api/README.md (Compaction section) for code examples. Full docs via WebFetch in shared/live-sources.md.
---
Prompt Caching (Quick Reference)
Prefix match. Any byte change anywhere in the prefix invalidates everything after it. Render order is tools → system → messages. Keep stable content first (frozen system prompt, deterministic tool list), put volatile content (timestamps, per-request IDs, varying questions) after the last cache_control breakpoint.
Top-level auto-caching (cache_control: {type: "ephemeral"} on messages.create()) is the simplest option when you don't need fine-grained placement. Max 4 breakpoints per request. Minimum cacheable prefix is ~1024 tokens — shorter prefixes silently won't cache.
Verify with `usage.cache_read_input_tokens` — if it's zero across repeated requests, a silent invalidator is at work (datetime.now() in system prompt, unsorted JSON, varying tool set).
For placement patterns, architectural guidance, and the silent-invalidator audit checklist: read shared/prompt-caching.md. Language-specific syntax: {lang}/claude-api/README.md (Prompt Caching section).
---
Managed Agents (Beta)
Managed Agents is a third surface: server-managed stateful agents with Anthropic-hosted tool execution. You create a persisted, versioned Agent config (POST /v1/agents), then start Sessions that reference it. Each session provisions a container as the agent's workspace — bash, file ops, and code execution run there; the agent loop itself runs on Anthropic's orchestration layer and acts on the container via tools. The session streams events; you send messages and tool results back.
Managed Agents is first-party only. It is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. For agents on third-party providers, use Claude API + tool use.
Mandatory flow: Agent (once) → Session (every run). model/system/tools live on the agent, never the session. See shared/managed-agents-overview.md for the full reading guide, beta headers, and pitfalls.
Beta headers: managed-agents-2026-04-01 — the SDK sets this automatically for all client.beta.{agents,environments,sessions,vaults}.* calls. Skills API uses skills-2025-10-02 and Files API uses files-api-2025-04-14, but you don't need to explicitly pass those in for endpoints other than /v1/skills and /v1/files.
Subcommands — invoke directly with /claude-api <subcommand>:
| Subcommand | Action |
|---|---|
managed-agents-onboard | Walk the user through setting up a Managed Agent from scratch. Read `shared/managed-agents-onboarding.md` immediately and follow its interview script: mental model → know-or-explore branch → template config → session setup → emit code. Do not summarize — run the interview. |
Reading guide: Start with shared/managed-agents-overview.md, then the topical shared/managed-agents-*.md files (core, environments, tools, events, client-patterns, onboarding, api-reference). For Python, TypeScript, Go, Ruby, PHP, and Java, read {lang}/managed-agents/README.md for code examples. For cURL, read curl/managed-agents.md. Agents are persistent — create once, reference by ID. Store the agent ID returned by agents.create and pass it to every subsequent 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 (URL in shared/live-sources.md). If a binding you need isn't shown in the language README, WebFetch the relevant entry from shared/live-sources.md rather than guess. C# does not currently have Managed Agents support; use raw HTTP from curl/managed-agents.md as a reference.
When the user wants to set up a Managed Agent from scratch (e.g. "how do I get started", "walk me through creating one", "set up a new agent"): read shared/managed-agents-onboarding.md and run its interview — same flow as the managed-agents-onboard subcommand.
When the user asks "how do I write the client code for X": reach for shared/managed-agents-client-patterns.md — covers lossless stream reconnect, processed_at queued/processed gate, interrupt, tool_confirmation round-trip, the correct idle/terminated break gate, post-idle status race, stream-first ordering, file-mount gotchas, keeping credentials host-side via custom tools, etc.
---
Reading Guide
After detecting the language, read the relevant files based on what the user needs:
Quick Task Reference
Single text classification/summarization/extraction/Q&A: → Read only {lang}/claude-api/README.md
Chat UI or real-time response display: → Read {lang}/claude-api/README.md + {lang}/claude-api/streaming.md
Long-running conversations (may exceed context window): → Read {lang}/claude-api/README.md — see Compaction section Migrating to a newer model (Opus 4.7 / Opus 4.6 / Sonnet 4.6) or replacing a retired model: → Read shared/model-migration.md Prompt caching / optimize caching / "why is my cache hit rate low": → Read shared/prompt-caching.md + {lang}/claude-api/README.md (Prompt Caching section)
Function calling / tool use / agents: → Read {lang}/claude-api/README.md + shared/tool-use-concepts.md + {lang}/claude-api/tool-use.md
Agent design (tool surface, context management, caching strategy): → Read shared/agent-design.md
Batch processing (non-latency-sensitive): → Read {lang}/claude-api/README.md + {lang}/claude-api/batches.md
File uploads across multiple requests: → Read {lang}/claude-api/README.md + {lang}/claude-api/files-api.md
Managed Agents (server-managed stateful agents with workspace): → Read shared/managed-agents-overview.md + the rest of the shared/managed-agents-*.md files. For Python, TypeScript, Go, Ruby, PHP, and Java, read {lang}/managed-agents/README.md for code examples. For cURL, read curl/managed-agents.md. Agents are persistent — create once, reference by ID. Store the agent ID returned by agents.create and pass it to every subsequent 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 (URL in shared/live-sources.md). If a binding you need isn't shown in the language README, WebFetch the relevant entry from shared/live-sources.md rather than guess. C# does not currently support Managed Agents — use raw HTTP from curl/managed-agents.md as a reference.
Claude API (Full File Reference)
Read the language-specific Claude API folder ({language}/claude-api/):
1. `{language}/claude-api/README.md` — Read this first. Installation, quick start, common patterns, error handling. 2. `shared/tool-use-concepts.md` — Read when the user needs function calling, code execution, memory, or structured outputs. Covers conceptual foundations. 3. `shared/agent-design.md` — Read when designing an agent: bash vs. dedicated tools, programmatic tool calling, tool search/skills, context editing vs. compaction vs. memory, caching principles. 4. `{language}/claude-api/tool-use.md` — Read for language-specific tool use code examples (tool runner, manual loop, code execution, memory, structured outputs). 5. `{language}/claude-api/streaming.md` — Read when building chat UIs or interfaces that display responses incrementally. 6. `{language}/claude-api/batches.md` — Read when processing many requests offline (not latency-sensitive). Runs asynchronously at 50% cost. 7. `{language}/claude-api/files-api.md` — Read when sending the same file across multiple requests without re-uploading. 8. `shared/prompt-caching.md` — Read when adding or optimizing prompt caching. Covers prefix-stability design, breakpoint placement, and anti-patterns that silently invalidate cache. 9. `shared/error-codes.md` — Read when debugging HTTP errors or implementing error handling. 10. `shared/model-migration.md` — Read when upgrading to newer models, replacing retired models, or translating budget_tokens / prefill patterns to the current API. 11. `shared/live-sources.md` — WebFetch URLs for fetching the latest official documentation.
Note: For Java, Go, Ruby, C#, PHP, and cURL — these have a single file each covering all basics. Read that file plusshared/tool-use-concepts.mdandshared/error-codes.mdas needed.
Note: For the Managed Agents file reference, see the## Managed Agents (Beta)section above — it lists everyshared/managed-agents-*.mdfile and the language-specific READMEs.
---
When to Use WebFetch
Use WebFetch to get the latest documentation when:
- User asks for "latest" or "current" information
- Cached data seems incorrect
- User asks about features not covered here
Live documentation URLs are in shared/live-sources.md.
Common Pitfalls
- Don't truncate inputs when passing files or content to the API. If the content is too long to fit in the context window, notify the user and discuss options (chunking, summarization, etc.) rather than silently truncating.
- Opus 4.7 thinking: Adaptive only.
thinking: {type: "enabled", budget_tokens: N}returns 400 on Opus 4.7 —budget_tokensis fully removed there (along withtemperature,top_p,top_k). Usethinking: {type: "adaptive"}. - Opus 4.6 / Sonnet 4.6 thinking: Use
thinking: {type: "adaptive"}— do NOT usebudget_tokensfor new 4.6 code (deprecated on both Opus 4.6 and Sonnet 4.6; for gradual migration of existing code, see the transitional escape hatch inshared/model-migration.md— note this carve-out does not apply to Opus 4.7). For older models,budget_tokensmust be less thanmax_tokens(minimum 1024). This will throw an error if you get it wrong. - 4.6/4.7 family prefill removed: Assistant message prefills (last-assistant-turn prefills) return a 400 error on Opus 4.6, Opus 4.7, and Sonnet 4.6. Use structured outputs (
output_config.format) or system prompt instructions to control response format instead. - Confirm migration scope before editing: When a user asks to migrate code to a newer Claude model without naming a specific file, directory, or file list, ask which scope to apply first — the entire working directory, a specific subdirectory, or a specific set of files. Do not start editing until the user confirms. Imperative phrasings like "migrate my codebase", "move my project to X", "upgrade to Sonnet 4.6", or bare "migrate to Opus 4.7" are still ambiguous — they tell you what to do but not where, so ask. Proceed without asking only when the prompt names an exact file, a specific directory, or an explicit file list ("migrate
app.py", "migrate everything underservices/", "updatea.pyandb.py"). Seeshared/model-migration.mdStep 0. - `max_tokens` defaults: Don't lowball
max_tokens— hitting the cap truncates output mid-thought and requires a retry. For non-streaming requests, default to~16000(keeps responses under SDK HTTP timeouts). For streaming requests, default to~64000(timeouts aren't a concern, so give the model room). Only go lower when you have a hard reason: classification (~256), cost caps, or deliberately short outputs. - 128K output tokens: Opus 4.6 and Opus 4.7 support up to 128K
max_tokens, but the SDKs require streaming for values that large to avoid HTTP timeouts. Use.stream()with.get_final_message()/.finalMessage(). - Tool call JSON parsing (4.6/4.7 family): Opus 4.6, Opus 4.7, and Sonnet 4.6 may produce different JSON string escaping in tool call
inputfields (e.g., Unicode or forward-slash escaping). Always parse tool inputs withjson.loads()/JSON.parse()— never do raw string matching on the serialized input. - Structured outputs (all models): Use
output_config: {format: {...}}instead of the deprecatedoutput_formatparameter onmessages.create(). This is a general API change, not 4.6-specific. - Don't reimplement SDK functionality: The SDK provides high-level helpers — use them instead of building from scratch. Specifically: use
stream.finalMessage()instead of wrapping.on()events innew Promise(); use typed exception classes (Anthropic.RateLimitError, etc.) instead of string-matching error messages; use SDK types (Anthropic.MessageParam,Anthropic.Tool,Anthropic.Message, etc.) instead of redefining equivalent interfaces. - Don't define custom types for SDK data structures: The SDK exports types for all API objects. Use
Anthropic.MessageParamfor messages,Anthropic.Toolfor tool definitions,Anthropic.ToolUseBlock/Anthropic.ToolResultBlockParamfor tool results,Anthropic.Messagefor responses. Defining your owninterface ChatMessage { role: string; content: unknown }duplicates what the SDK already provides and loses type safety. - Report and document output: For tasks that produce reports, documents, or visualizations, the code execution sandbox has
python-docx,python-pptx,matplotlib,pillow, andpypdfpre-installed. Claude can generate formatted files (DOCX, PDF, charts) and return them via the Files API — consider this for "report" or "document" type requests instead of plain stdout text.
Claude API — C#
Note: The C# SDK is the official Anthropic SDK for C#. Tool use is supported via the Messages API. A class-annotation-based tool runner is not available; use raw tool definitions with JSON schema. The SDK also supports Microsoft.Extensions.AI IChatClient integration with function invocation.
Installation
dotnet add package AnthropicClient Initialization
using Anthropic;
// Default (uses ANTHROPIC_API_KEY env var)
AnthropicClient client = new();
// Explicit API key (use environment variables — never hardcode keys)
AnthropicClient client = new() {
ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
};---
Basic Message Request
using Anthropic.Models.Messages;
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus4_6,
MaxTokens = 16000,
Messages = [new() { Role = Role.User, Content = "What is the capital of France?" }]
};
var response = await client.Messages.Create(parameters);
// ContentBlock is a union wrapper. .Value unwraps to the variant object,
// then OfType<T> filters to the type you want. Or use the TryPick* idiom
// shown in the Thinking section below.
foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())
{
Console.WriteLine(text.Text);
}---
Streaming
using Anthropic.Models.Messages;
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus4_6,
MaxTokens = 64000,
Messages = [new() { Role = Role.User, Content = "Write a haiku" }]
};
await foreach (RawMessageStreamEvent streamEvent in client.Messages.CreateStreaming(parameters))
{
if (streamEvent.TryPickContentBlockDelta(out var delta) &&
delta.Delta.TryPickText(out var text))
{
Console.Write(text.Text);
}
}`RawMessageStreamEvent` TryPick methods (naming drops the Message/Raw prefix): TryPickStart, TryPickDelta, TryPickStop, TryPickContentBlockStart, TryPickContentBlockDelta, TryPickContentBlockStop. There is no TryPickMessageStop — use TryPickStop.
---
Thinking
Adaptive thinking is the recommended mode for Claude 4.6+ models. Claude decides dynamically when and how much to think.
using Anthropic.Models.Messages;
var response = await client.Messages.Create(new MessageCreateParams
{
Model = Model.ClaudeOpus4_6,
MaxTokens = 16000,
// ThinkingConfigParam? implicitly converts from the concrete variant classes —
// no wrapper needed.
Thinking = new ThinkingConfigAdaptive(),
Messages =
[
new() { Role = Role.User, Content = "Solve: 27 * 453" },
],
});
// ThinkingBlock(s) precede TextBlock in Content. TryPick* narrows the union.
foreach (var block in response.Content)
{
if (block.TryPickThinking(out ThinkingBlock? t))
{
Console.WriteLine($"[thinking] {t.Thinking}");
}
else if (block.TryPickText(out TextBlock? text))
{
Console.WriteLine(text.Text);
}
}Deprecated: new ThinkingConfigEnabled { BudgetTokens = N } (fixed-budget extended thinking) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.Alternative to TryPick*: .Select(b => b.Value).OfType<ThinkingBlock>() (same LINQ pattern as the Basic Message example).
---
Tool Use
Defining a tool
Tool (NOT ToolParam) with an InputSchema record. InputSchema.Type is auto-set to "object" by the constructor — don't set it. ToolUnion has an implicit conversion from Tool, triggered by the collection expression [...].
using System.Text.Json;
using Anthropic.Models.Messages;
var parameters = new MessageCreateParams
{
Model = Model.ClaudeSonnet4_6,
MaxTokens = 16000,
Tools = [
new Tool {
Name = "get_weather",
Description = "Get the current weather in a given location",
InputSchema = new() {
Properties = new Dictionary<string, JsonElement> {
["location"] = JsonSerializer.SerializeToElement(
new { type = "string", description = "City name" }),
},
Required = ["location"],
},
},
],
Messages = [new() { Role = Role.User, Content = "Weather in Paris?" }],
};Derived from anthropic-sdk-csharp/src/Anthropic/Models/Messages/Tool.cs and ToolUnion.cs:799 (implicit conversion).
See shared tool use concepts for the loop pattern.
Converting response content to the follow-up assistant message
When echoing Claude's response back in the assistant turn, there is no `.ToParam()` helper — manually reconstruct each ContentBlock variant as its *Param counterpart. Do NOT use new ContentBlockParam(block.Json): it compiles and serializes, but .Value stays null so TryPick*/Validate() fail (degraded JSON pass-through, not the typed path).
using Anthropic.Models.Messages;
Message response = await client.Messages.Create(parameters);
// No .ToParam() — reconstruct per variant. Implicit conversions from each
// *Param type to ContentBlockParam mean no explicit wrapper.
List<ContentBlockParam> assistantContent = [];
List<ContentBlockParam> toolResults = [];
foreach (ContentBlock block in response.Content)
{
if (block.TryPickText(out TextBlock? text))
{
assistantContent.Add(new TextBlockParam { Text = text.Text });
}
else if (block.TryPickThinking(out ThinkingBlock? thinking))
{
// Signature MUST be preserved — the API rejects tampering
assistantContent.Add(new ThinkingBlockParam
{
Thinking = thinking.Thinking,
Signature = thinking.Signature,
});
}
else if (block.TryPickRedactedThinking(out RedactedThinkingBlock? redacted))
{
assistantContent.Add(new RedactedThinkingBlockParam { Data = redacted.Data });
}
else if (block.TryPickToolUse(out ToolUseBlock? toolUse))
{
// ToolUseBlock has required Caller; ToolUseBlockParam.Caller is optional — don't copy it
assistantContent.Add(new ToolUseBlockParam
{
ID = toolUse.ID,
Name = toolUse.Name,
Input = toolUse.Input,
});
// Execute the tool; collect ONE result per tool_use block — the API
// rejects the follow-up if any tool_use ID lacks a matching tool_result.
string result = ExecuteYourTool(toolUse.Name, toolUse.Input);
toolResults.Add(new ToolResultBlockParam
{
ToolUseID = toolUse.ID,
Content = result,
});
}
}
// Follow-up: prior messages + assistant echo + user tool_result(s)
List<MessageParam> followUpMessages =
[
.. parameters.Messages,
new() { Role = Role.Assistant, Content = assistantContent },
new() { Role = Role.User, Content = toolResults },
];ToolResultBlockParam has no tuple constructor — use the object initializer. Content is a string-or-list union; a plain string implicitly converts.
---
Context Editing / Compaction (Beta)
Beta-namespace prefix is inconsistent (source-verified against src/Anthropic/Models/Beta/Messages/*.cs @ 12.9.0). No prefix: MessageCreateParams, MessageCountTokensParams, Role. Everything else has the `Beta` prefix: BetaMessageParam, BetaMessage, BetaContentBlock, BetaToolUseBlock, all block param types. The unprefixed Role WILL collide with Anthropic.Models.Messages.Role if you import both namespaces (CS0104). Safest: import only Beta; if mixing, alias the beta Role:
using Anthropic.Models.Beta.Messages;
using NonBeta = Anthropic.Models.Messages; // only if you also need non-beta types
// Now: MessageCreateParams, BetaMessageParam, Role (beta's), NonBeta.Role (if needed)BetaMessage.Content is IReadOnlyList<BetaContentBlock> — a 15-variant discriminated union. Narrow with TryPick*. Response `BetaContentBlock` is NOT assignable to param `BetaContentBlockParam` — there's no .ToParam() in C#. Round-trip by converting each block:
using Anthropic.Models.Beta.Messages;
var betaParams = new MessageCreateParams // no Beta prefix — one of only 2 unprefixed
{
Model = Model.ClaudeOpus4_6,
MaxTokens = 16000,
Betas = ["compact-2026-01-12"],
ContextManagement = new BetaContextManagementConfig
{
Edits = [new BetaCompact20260112Edit()],
},
Messages = messages,
};
BetaMessage resp = await client.Beta.Messages.Create(betaParams);
foreach (BetaContentBlock block in resp.Content)
{
if (block.TryPickCompaction(out BetaCompactionBlock? compaction))
{
// Content is nullable — compaction can fail server-side
Console.WriteLine($"compaction summary: {compaction.Content}");
}
}
// Context-edit metadata lives on a separate nullable field
if (resp.ContextManagement is { } ctx)
{
foreach (var edit in ctx.AppliedEdits)
Console.WriteLine($"cleared {edit.ClearedInputTokens} tokens");
}
// ROUND-TRIP: BetaMessageParam.Content is BetaMessageParamContent (a string|list
// union). It implicit-converts from List<BetaContentBlockParam>, NOT from the
// response's IReadOnlyList<BetaContentBlock>. Convert each block:
List<BetaContentBlockParam> paramBlocks = [];
foreach (var b in resp.Content)
{
if (b.TryPickText(out var t)) paramBlocks.Add(new BetaTextBlockParam { Text = t.Text });
else if (b.TryPickCompaction(out var c)) paramBlocks.Add(new BetaCompactionBlockParam { Content = c.Content });
// ... other variants as needed
}
messages.Add(new BetaMessageParam { Role = Role.Assistant, Content = paramBlocks });All 15 BetaContentBlock.TryPick* variants: Text, Thinking, RedactedThinking, ToolUse, ServerToolUse, WebSearchToolResult, WebFetchToolResult, CodeExecutionToolResult, BashCodeExecutionToolResult, TextEditorCodeExecutionToolResult, ToolSearchToolResult, McpToolUse, McpToolResult, ContainerUpload, Compaction.
`BetaToolUseBlock.Input` is `IReadOnlyDictionary<string, JsonElement>` — index by key then call the JsonElement extractor:
if (block.TryPickToolUse(out BetaToolUseBlock? tu))
{
int a = tu.Input["a"].GetInt32();
string s = tu.Input["name"].GetString()!;
}---
Effort Parameter
Effort is nested under OutputConfig, NOT a top-level property. ApiEnum<string, Effort> has an implicit conversion from the enum, so assign Effort.High directly.
OutputConfig = new OutputConfig { Effort = Effort.High },Values: Effort.Low, Effort.Medium, Effort.High, Effort.Max. Combine with Thinking = new ThinkingConfigAdaptive() for cost-quality control.
---
Prompt Caching
System takes MessageCreateParamsSystem? — a union of string or List<TextBlockParam>. There is no SystemTextBlockParam; use plain TextBlockParam. The implicit conversion needs the concrete List<TextBlockParam> type (array literals won't convert). For placement patterns and the silent-invalidator audit checklist, see shared/prompt-caching.md.
System = new List<TextBlockParam> {
new() {
Text = longSystemPrompt,
CacheControl = new CacheControlEphemeral(), // auto-sets Type = "ephemeral"
},
},Optional Ttl on CacheControlEphemeral: new() { Ttl = Ttl.Ttl1h } or Ttl.Ttl5m. CacheControl also exists on Tool.CacheControl and top-level MessageCreateParams.CacheControl.
Verify hits via response.Usage.CacheCreationInputTokens / response.Usage.CacheReadInputTokens.
---
Token Counting
MessageTokensCount result = await client.Messages.CountTokens(new MessageCountTokensParams {
Model = Model.ClaudeOpus4_6,
Messages = [new() { Role = Role.User, Content = "Hello" }],
});
long tokens = result.InputTokens;MessageCountTokensParams.Tools uses a different union type (MessageCountTokensTool) than MessageCreateParams.Tools (ToolUnion) — if you're passing tools, the compiler will tell you when it matters.
---
Structured Output
OutputConfig = new OutputConfig {
Format = new JsonOutputFormat {
Schema = new Dictionary<string, JsonElement> {
["type"] = JsonSerializer.SerializeToElement("object"),
["properties"] = JsonSerializer.SerializeToElement(
new { name = new { type = "string" } }),
["required"] = JsonSerializer.SerializeToElement(new[] { "name" }),
},
},
},JsonOutputFormat.Type is auto-set to "json_schema" by the constructor. Schema is required.
---
PDF / Document Input
DocumentBlockParam takes a DocumentBlockParamSource union: Base64PdfSource / UrlPdfSource / PlainTextSource / ContentBlockSource. Base64PdfSource auto-sets MediaType = "application/pdf" and Type = "base64".
new MessageParam {
Role = Role.User,
Content = new List<ContentBlockParam> {
new DocumentBlockParam { Source = new Base64PdfSource { Data = base64String } },
new TextBlockParam { Text = "Summarize this PDF" },
},
}---
Server-Side Tools
Web search, bash, text editor, and code execution are built-in server tools. Type names are version-suffixed; constructors auto-set name/type. All implicit-convert to ToolUnion.
Tools = [
new WebSearchTool20260209(),
new ToolBash20250124(),
new ToolTextEditor20250728(),
new CodeExecutionTool20260120(),
],Also available: WebFetchTool20260209, MemoryTool20250818. WebSearchTool20260209 optionals: AllowedDomains, BlockedDomains, MaxUses, UserLocation.
---
Files API (Beta)
Files live under client.Beta.Files (namespace Anthropic.Models.Beta.Files). BinaryContent implicit-converts from Stream and byte[].
using Anthropic.Models.Beta.Files;
using Anthropic.Models.Beta.Messages;
FileMetadata meta = await client.Beta.Files.Upload(
new FileUploadParams { File = File.OpenRead("doc.pdf") });
// Referencing the uploaded file requires Beta message types:
new BetaRequestDocumentBlock {
Source = new BetaFileDocumentSource { FileID = meta.ID },
}The non-beta DocumentBlockParamSource union has no file-ID variant — file references need client.Beta.Messages.Create().
Claude API — cURL / Raw HTTP
Use these examples when the user needs raw HTTP requests or is working in a language without an official SDK.
Setup
export ANTHROPIC_API_KEY="your-api-key"---
Basic Message Request
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 16000,
"messages": [
{"role": "user", "content": "What is the capital of France?"}
]
}'Parsing the response
Use jq to extract fields from the JSON response. Do not use grep/sed — JSON strings can contain any character and regex parsing will break on quotes, escapes, or multi-line content.
# Capture the response, then extract fields
response=$(curl -s https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{"model":"claude-opus-4-7","max_tokens":16000,"messages":[{"role":"user","content":"Hello"}]}')
# Print the first text block (-r strips the JSON quotes)
echo "$response" | jq -r '.content[0].text'
# Read usage fields
input_tokens=$(echo "$response" | jq -r '.usage.input_tokens')
output_tokens=$(echo "$response" | jq -r '.usage.output_tokens')
# Read stop reason (for tool-use loops)
stop_reason=$(echo "$response" | jq -r '.stop_reason')
# Extract all text blocks (content is an array; filter to type=="text")
echo "$response" | jq -r '.content[] | select(.type == "text") | .text'---
Streaming (SSE)
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 64000,
"stream": true,
"messages": [{"role": "user", "content": "Write a haiku"}]
}'The response is a stream of Server-Sent Events:
event: message_start
data: {"type":"message_start","message":{"id":"msg_...","type":"message",...}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":12}}
event: message_stop
data: {"type":"message_stop"}---
Tool Use
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 16000,
"tools": [{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}],
"messages": [{"role": "user", "content": "What is the weather in Paris?"}]
}'When Claude responds with a tool_use block, send the result back:
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 16000,
"tools": [{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}],
"messages": [
{"role": "user", "content": "What is the weather in Paris?"},
{"role": "assistant", "content": [
{"type": "text", "text": "Let me check the weather."},
{"type": "tool_use", "id": "toolu_abc123", "name": "get_weather", "input": {"location": "Paris"}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_abc123", "content": "72°F and sunny"}
]}
]
}'---
Prompt Caching
Put cache_control on the last block of the stable prefix. See shared/prompt-caching.md for placement patterns and the silent-invalidator audit checklist.
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 16000,
"system": [
{"type": "text", "text": "<large shared prompt...>", "cache_control": {"type": "ephemeral"}}
],
"messages": [{"role": "user", "content": "Summarize the key points"}]
}'For 1-hour TTL: "cache_control": {"type": "ephemeral", "ttl": "1h"}. Top-level "cache_control" on the request body auto-places on the last cacheable block. Verify hits via the response usage.cache_creation_input_tokens / usage.cache_read_input_tokens fields.
---
Extended Thinking
Opus 4.7, Opus 4.6, and Sonnet 4.6: Use adaptive thinking. budget_tokens is removed on Opus 4.7 (400 if sent); deprecated on Opus 4.6 and Sonnet 4.6.Older models: Use"type": "enabled"with"budget_tokens": N(must be <max_tokens, min 1024).
# Opus 4.7 / 4.6: adaptive thinking (recommended)
curl https://api.anthropic.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 16000,
"thinking": {
"type": "adaptive"
},
"output_config": {
"effort": "high"
},
"messages": [{"role": "user", "content": "Solve this step by step..."}]
}'---
Required Headers
| Header | Value | Description |
|---|---|---|
Content-Type | application/json | Required |
x-api-key | Your API key | Authentication |
anthropic-version | 2023-06-01 | API version |
anthropic-beta | Beta feature IDs | Required for beta features |
Managed Agents — cURL / Raw HTTP
Use these examples when the user needs raw HTTP requests or is working without an SDK.
Setup
export ANTHROPIC_API_KEY="your-api-key"
# Common headers
HEADERS=(
-H "Content-Type: application/json"
-H "x-api-key: $ANTHROPIC_API_KEY"
-H "anthropic-version: 2023-06-01"
-H "anthropic-beta: managed-agents-2026-04-01"
)---
Create an Environment
curl -X POST https://api.anthropic.com/v1/environments \
"${HEADERS[@]}" \
-d '{
"name": "my-dev-env",
"config": {
"type": "cloud",
"networking": { "type": "unrestricted" }
}
}'With restricted networking
curl -X POST https://api.anthropic.com/v1/environments \
"${HEADERS[@]}" \
-d '{
"name": "restricted-env",
"config": {
"type": "cloud",
"networking": {
"type": "package_managers_and_custom",
"allowed_hosts": ["api.example.com"]
}
}
}'---
Create an Agent (required first step)
⚠️ There is no inline agent config. Undermanaged-agents-2026-04-01,model/system/toolsare top-level fields onPOST /v1/agents, not on the session. Always create the agent first — the session only takes"agent": {"type": "agent", "id": "..."}.
Minimal
# 1. Create the agent
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "Coding Assistant",
"model": "claude-opus-4-7",
"tools": [{ "type": "agent_toolset_20260401" }]
}'
# → { "id": "agent_abc123", ... }
# 2. Start a session
curl -X POST https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}" \
-d '{
"agent": { "type": "agent", "id": "agent_abc123", "version": "1772585501101368014" },
"environment_id": "env_abc123"
}'With system prompt, custom tools, and GitHub repo
# 1. Create the agent
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "Code Reviewer",
"model": "claude-opus-4-7",
"system": "You are a senior code reviewer. Be thorough and constructive.",
"tools": [
{ "type": "agent_toolset_20260401" },
{
"type": "custom",
"name": "run_linter",
"description": "Run the project linter on a file",
"input_schema": {
"type": "object",
"properties": {
"file_path": { "type": "string", "description": "Path to lint" }
},
"required": ["file_path"]
}
}
]
}'
# 2. Start a session with the repo mounted
curl -X POST https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}" \
-d '{
"agent": { "type": "agent", "id": "agent_abc123", "version": "1772585501101368014" },
"environment_id": "env_abc123",
"title": "Code review session",
"resources": [
{
"type": "github_repository",
"url": "https://github.com/owner/repo",
"mount_path": "/workspace/repo",
"authorization_token": "ghp_...",
"branch": "feature-branch"
}
]
}'---
Send a User Message
curl -X POST https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}" \
-d '{
"events": [
{
"type": "user.message",
"content": [{ "type": "text", "text": "Review the auth module for security issues" }]
}
]
}'---
Stream Events (SSE)
curl -N https://api.anthropic.com/v1/sessions/$SESSION_ID/events/stream \
"${HEADERS[@]}"Response format:
event: session.status_running
data: {"type":"session.status_running","id":"sevt_...","processed_at":"..."}
event: agent.message
data: {"type":"agent.message","id":"sevt_...","content":[{"type":"text","text":"I'll review..."}],"processed_at":"..."}
event: session.status_idle
data: {"type":"session.status_idle","id":"sevt_...","processed_at":"..."}---
Poll Events
# Get all events
curl https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}"
# Paginated — get next page of events
curl "https://api.anthropic.com/v1/sessions/$SESSION_ID/events?page=page_abc123" \
"${HEADERS[@]}"---
Provide Custom Tool Result
When the agent calls a custom tool, send the result back:
curl -X POST https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}" \
-d '{
"events": [
{
"type": "user.custom_tool_result",
"custom_tool_use_id": "sevt_abc123",
"content": [{ "type": "text", "text": "No linting errors found." }]
}
]
}'---
Interrupt a Running Session
curl -X POST https://api.anthropic.com/v1/sessions/$SESSION_ID/events \
"${HEADERS[@]}" \
-d '{
"events": [
{
"type": "interrupt"
}
]
}'---
Get Session Details
curl https://api.anthropic.com/v1/sessions/$SESSION_ID \
"${HEADERS[@]}"---
List Sessions
curl https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}"---
Delete a Session
curl -X DELETE https://api.anthropic.com/v1/sessions/$SESSION_ID \
"${HEADERS[@]}"---
Upload a File
curl -X POST https://api.anthropic.com/v1/files \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14" \
-F "file=@path/to/file.txt" \
-F "purpose=agent"---
List and Download Session Files
List files the agent wrote to /mnt/session/outputs/ during a session, then download them.
# List files associated with a session
curl "https://api.anthropic.com/v1/files?scope_id=$SESSION_ID" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14,managed-agents-2026-04-01"
# Download a specific file
curl "https://api.anthropic.com/v1/files/$FILE_ID/content" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14,managed-agents-2026-04-01" \
-o downloaded_file.txt---
List Agents
curl https://api.anthropic.com/v1/agents \
"${HEADERS[@]}"---
MCP Server Integration
# 1. Agent declares MCP server (no auth here — auth goes in a vault)
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "MCP Agent",
"model": "claude-opus-4-7",
"mcp_servers": [
{ "type": "url", "name": "my-tools", "url": "https://my-mcp-server.example.com/sse" }
],
"tools": [
{ "type": "agent_toolset_20260401" },
{ "type": "mcp_toolset", "mcp_server_name": "my-tools" }
]
}'
# 2. Session attaches vault containing credentials for that MCP server URL
curl -X POST https://api.anthropic.com/v1/sessions \
"${HEADERS[@]}" \
-d '{
"agent": "agent_abc123",
"environment_id": "env_abc123",
"vault_ids": ["vlt_abc123"]
}'See shared/managed-agents-tools.md §Vaults for creating vaults and adding credentials.
---
Tool Configuration
curl -X POST https://api.anthropic.com/v1/agents \
"${HEADERS[@]}" \
-d '{
"name": "Restricted Agent",
"model": "claude-opus-4-7",
"tools": [
{
"type": "agent_toolset_20260401",
"default_config": { "enabled": true },
"configs": [
{ "name": "bash", "enabled": false }
]
}
]
}'Claude API — Go
Note: The Go SDK supports the Claude API and beta tool use with BetaToolRunner. Agent SDK is not yet available for Go.Installation
go get github.com/anthropics/anthropic-sdk-goClient Initialization
import (
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
// Default (uses ANTHROPIC_API_KEY env var)
client := anthropic.NewClient()
// Explicit API key
client := anthropic.NewClient(
option.WithAPIKey("your-api-key"),
)---
Basic Message Request
response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_6,
MaxTokens: 16000,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is the capital of France?")),
},
})
if err != nil {
log.Fatal(err)
}
for _, block := range response.Content {
switch variant := block.AsAny().(type) {
case anthropic.TextBlock:
fmt.Println(variant.Text)
}
}---
Streaming
stream := client.Messages.NewStreaming(context.Background(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_6,
MaxTokens: 64000,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Write a haiku")),
},
})
for stream.Next() {
event := stream.Current()
switch eventVariant := event.AsAny().(type) {
case anthropic.ContentBlockDeltaEvent:
switch deltaVariant := eventVariant.Delta.AsAny().(type) {
case anthropic.TextDelta:
fmt.Print(deltaVariant.Text)
}
}
}
if err := stream.Err(); err != nil {
log.Fatal(err)
}Accumulating the final message (there is no GetFinalMessage() on the stream):
stream := client.Messages.NewStreaming(ctx, params)
message := anthropic.Message{}
for stream.Next() {
message.Accumulate(stream.Current())
}
if err := stream.Err(); err != nil { log.Fatal(err) }
// message.Content now has the complete response---
Tool Use
Tool Runner (Beta — Recommended)
Beta: The Go SDK provides BetaToolRunner for automatic tool use loops via the toolrunner package.
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/toolrunner"
)
// Define tool input with jsonschema tags for automatic schema generation
type GetWeatherInput struct {
City string `json:"city" jsonschema:"required,description=The city name"`
}
// Create a tool with automatic schema generation from struct tags
weatherTool, err := toolrunner.NewBetaToolFromJSONSchema(
"get_weather",
"Get current weather for a city",
func(ctx context.Context, input GetWeatherInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
return anthropic.BetaToolResultBlockParamContentUnion{
OfText: &anthropic.BetaTextBlockParam{
Text: fmt.Sprintf("The weather in %s is sunny, 72°F", input.City),
},
}, nil
},
)
if err != nil {
log.Fatal(err)
}
// Create a tool runner that handles the conversation loop automatically
runner := client.Beta.Messages.NewToolRunner(
[]anthropic.BetaTool{weatherTool},
anthropic.BetaToolRunnerParams{
BetaMessageNewParams: anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeOpus4_6,
MaxTokens: 16000,
Messages: []anthropic.BetaMessageParam{
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Paris?")),
},
},
MaxIterations: 5,
},
)
// Run until Claude produces a final response
message, err := runner.RunToCompletion(context.Background())
if err != nil {
log.Fatal(err)
}
// RunToCompletion returns *BetaMessage; content is []BetaContentBlockUnion.
// Narrow via AsAny() switch — note the Beta-namespace types (BetaTextBlock,
// not TextBlock):
for _, block := range message.Content {
switch block := block.AsAny().(type) {
case anthropic.BetaTextBlock:
fmt.Println(block.Text)
}
}Key features of the Go tool runner:
- Automatic schema generation from Go structs via
jsonschematags RunToCompletion()for simple one-shot usageAll()iterator for processing each message in the conversationNextMessage()for step-by-step iteration- Streaming variant via
NewToolRunnerStreaming()withAllStreaming()
Manual Loop
For fine-grained control over the agentic loop, define tools with ToolParam, check StopReason, execute tools yourself, and feed tool_result blocks back. This is the pattern when you need to intercept, validate, or log tool calls.
Derived from anthropic-sdk-go/examples/tools/main.go.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient()
// 1. Define tools. ToolParam.InputSchema uses a map, no struct tags needed.
addTool := anthropic.ToolParam{
Name: "add",
Description: anthropic.String("Add two integers"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"a": map[string]any{"type": "integer"},
"b": map[string]any{"type": "integer"},
},
},
}
// ToolParam must be wrapped in ToolUnionParam for the Tools slice
tools := []anthropic.ToolUnionParam{{OfTool: &addTool}}
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is 2 + 3?")),
}
for {
resp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeSonnet4_6,
MaxTokens: 16000,
Messages: messages,
Tools: tools,
})
if err != nil {
log.Fatal(err)
}
// 2. Append the assistant response to history BEFORE processing tool calls.
// resp.ToParam() converts Message → MessageParam in one call.
messages = append(messages, resp.ToParam())
// 3. Walk content blocks. ContentBlockUnion is a flattened struct;
// use block.AsAny().(type) to switch on the actual variant.
toolResults := []anthropic.ContentBlockParamUnion{}
for _, block := range resp.Content {
switch variant := block.AsAny().(type) {
case anthropic.TextBlock:
fmt.Println(variant.Text)
case anthropic.ToolUseBlock:
// 4. Parse the tool input. Use variant.JSON.Input.Raw() to get the
// raw JSON — block.Input is json.RawMessage, not the parsed value.
var in struct {
A int `json:"a"`
B int `json:"b"`
}
if err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &in); err != nil {
log.Fatal(err)
}
result := fmt.Sprintf("%d", in.A+in.B)
// 5. NewToolResultBlock(toolUseID, content, isError) builds the
// ContentBlockParamUnion for you. block.ID is the tool_use_id.
toolResults = append(toolResults,
anthropic.NewToolResultBlock(block.ID, result, false))
}
}
// 6. Exit when Claude stops asking for tools
if resp.StopReason != anthropic.StopReasonToolUse {
break
}
// 7. Tool results go in a user message (variadic: all results in one turn)
messages = append(messages, anthropic.NewUserMessage(toolResults...))
}
}Key API surface:
| Symbol | Purpose |
|---|---|
resp.ToParam() | Convert Message response → MessageParam for history |
block.AsAny().(type) | Type-switch on ContentBlockUnion variants |
variant.JSON.Input.Raw() | Raw JSON string of tool input (for json.Unmarshal) |
anthropic.NewToolResultBlock(id, content, isError) | Build tool_result block |
anthropic.NewUserMessage(blocks...) | Wrap tool results as a user turn |
anthropic.StopReasonToolUse | StopReason constant to check loop termination |
anthropic.ToolUnionParam{OfTool: &t} | Wrap ToolParam in the union for Tools: |
---
Thinking
Enable Claude's internal reasoning by setting Thinking in MessageNewParams. The response will contain ThinkingBlock content before the final TextBlock.
Adaptive thinking is the recommended mode for Claude 4.6+ models. Claude decides dynamically when and how much to think. Combine with the effort parameter for cost-quality control.
Derived from anthropic-sdk-go/message.go (ThinkingConfigParamUnion, NewThinkingConfigAdaptiveParam).
// There is no ThinkingConfigParamOfAdaptive helper — construct the union
// struct-literal directly and take the address of the variant.
adaptive := anthropic.NewThinkingConfigAdaptiveParam()
params := anthropic.MessageNewParams{
Model: anthropic.ModelClaudeSonnet4_6,
MaxTokens: 16000,
Thinking: anthropic.ThinkingConfigParamUnion{OfAdaptive: &adaptive},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("How many r's in strawberry?")),
},
}
resp, err := client.Messages.New(context.Background(), params)
if err != nil {
log.Fatal(err)
}
// ThinkingBlock(s) precede TextBlock in content
for _, block := range resp.Content {
switch b := block.AsAny().(type) {
case anthropic.ThinkingBlock:
fmt.Println("[thinking]", b.Thinking)
case anthropic.TextBlock:
fmt.Println(b.Text)
}
}Deprecated: ThinkingConfigParamOfEnabled(budgetTokens) (fixed-budget extended thinking) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.To disable: anthropic.ThinkingConfigParamUnion{OfDisabled: &anthropic.ThinkingConfigDisabledParam{}}.
---
Prompt Caching
System is []TextBlockParam; set CacheControl on the last block to cache tools + system together. For placement patterns and the silent-invalidator audit checklist, see shared/prompt-caching.md.
System: []anthropic.TextBlockParam{{
Text: longSystemPrompt,
CacheControl: anthropic.NewCacheControlEphemeralParam(), // default 5m TTL
}},For 1-hour TTL: anthropic.CacheControlEphemeralParam{TTL: anthropic.CacheControlEphemeralTTLTTL1h}. There's also a top-level CacheControl on MessageNewParams that auto-places on the last cacheable block.
Verify hits via resp.Usage.CacheCreationInputTokens / resp.Usage.CacheReadInputTokens.
---
Server-Side Tools
Version-suffixed struct names with Param suffix. Name/Type are constant.* types — zero value marshals correctly, so {} works. Wrap in ToolUnionParam with the matching Of* field.
Tools: []anthropic.ToolUnionParam{
{OfWebSearchTool20260209: &anthropic.WebSearchTool20260209Param{}},
{OfBashTool20250124: &anthropic.ToolBash20250124Param{}},
{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
},Also available: WebFetchTool20260209Param, MemoryTool20250818Param, ToolSearchToolBm25_20251119Param, ToolSearchToolRegex20251119Param.
---
PDF / Document Input
NewDocumentBlock generic helper accepts any source type. MediaType/Type are auto-set.
b64 := base64.StdEncoding.EncodeToString(pdfBytes)
msg := anthropic.NewUserMessage(
anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{Data: b64}),
anthropic.NewTextBlock("Summarize this document"),
)Other sources: URLPDFSourceParam{URL: "https://..."}, PlainTextSourceParam{Data: "..."}.
---
Files API (Beta)
Under client.Beta.Files. Method is `Upload` (NOT New/Create), params struct is BetaFileUploadParams. The File field takes an io.Reader; use anthropic.File() to attach a filename + content-type for the multipart encoding.
f, _ := os.Open("./upload_me.txt")
defer f.Close()
meta, err := client.Beta.Files.Upload(ctx, anthropic.BetaFileUploadParams{
File: anthropic.File(f, "upload_me.txt", "text/plain"),
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaFilesAPI2025_04_14},
})
// meta.ID is the file_id to reference in subsequent message requestsOther Beta.Files methods: List, Delete, Download, GetMetadata.
---
Context Editing / Compaction (Beta)
Use Beta.Messages.New with ContextManagement on BetaMessageNewParams. There is no NewBetaAssistantMessage — use .ToParam() for the round-trip.
params := anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeOpus4_6, // also supported: ModelClaudeSonnet4_6
MaxTokens: 16000,
Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},
ContextManagement: anthropic.BetaContextManagementConfigParam{
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},
},
},
Messages: []anthropic.BetaMessageParam{ /* ... */ },
}
resp, err := client.Beta.Messages.New(ctx, params)
if err != nil {
log.Fatal(err)
}
// Round-trip: append response to history via .ToParam()
params.Messages = append(params.Messages, resp.ToParam())
// Read compaction blocks from the response
for _, block := range resp.Content {
if c, ok := block.AsAny().(anthropic.BetaCompactionBlock); ok {
fmt.Println("compaction summary:", c.Content)
}
}Other edit types: BetaClearToolUses20250919EditParam, BetaClearThinking20251015EditParam.
Managed Agents — Go
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.Agents are persistent — create once, reference by ID. Store the agent ID returned byagents.Newand pass it to every subsequentsessions.New; do not callagents.Newin the request path. The Anthropic CLI is one convenient way to create agents and environments from version-controlled YAML — its URL is inshared/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.
Installation
go get github.com/anthropics/anthropic-sdk-goClient Initialization
import (
"context"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
// Default (uses ANTHROPIC_API_KEY env var)
client := anthropic.NewClient()
// Explicit API key
client := anthropic.NewClient(
option.WithAPIKey("your-api-key"),
)
ctx := context.Background()---
Create an Environment
environment, err := client.Beta.Environments.New(ctx, anthropic.BetaEnvironmentNewParams{
Name: "my-dev-env",
Config: anthropic.BetaCloudConfigParams{
Networking: anthropic.BetaCloudConfigParamsNetworkingUnion{
OfUnrestricted: &anthropic.UnrestrictedNetworkParam{},
},
},
})
if err != nil {
panic(err)
}
fmt.Println(environment.ID) // env_...---
Create an Agent (required first step)
⚠️ There is no inline agent config.Model/System/Toolslive on the agent object, not the session. Always start withBeta.Agents.New()— the session only takesAgent: anthropic.BetaSessionNewParamsAgentUnion{OfString: anthropic.String(agent.ID)}(or the typedOfBetaManagedAgentsAgentsvariant when you need a specific version).
Minimal
// 1. Create the agent (reusable, versioned)
agent, err := client.Beta.Agents.New(ctx, anthropic.BetaAgentNewParams{
Name: "Coding Assistant",
Model: anthropic.BetaManagedAgentsModelConfigParams{
ID: "claude-opus-4-7",
Type: anthropic.BetaManagedAgentsModelConfigParamsTypeModelConfig,
},
System: anthropic.String("You are a helpful coding assistant."),
Tools: []anthropic.BetaAgentNewParamsToolUnion{{
OfAgentToolset20260401: &anthropic.BetaManagedAgentsAgentToolset20260401Params{
Type: anthropic.BetaManagedAgentsAgentToolset20260401ParamsTypeAgentToolset20260401,
},
}},
})
if err != nil {
panic(err)
}
// 2. Start a session
session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
Agent: anthropic.BetaSessionNewParamsAgentUnion{
OfBetaManagedAgentsAgents: &anthropic.BetaManagedAgentsAgentParams{
Type: anthropic.BetaManagedAgentsAgentParamsTypeAgent,
ID: agent.ID,
Version: anthropic.Int(agent.Version),
},
},
EnvironmentID: environment.ID,
Title: anthropic.String("Quickstart session"),
})
if err != nil {
panic(err)
}
fmt.Printf("Session ID: %s, status: %s\n", session.ID, session.Status)Updating an Agent
Updates create new versions; the agent object is immutable per version.
updatedAgent, err := client.Beta.Agents.Update(ctx, agent.ID, anthropic.BetaAgentUpdateParams{
Version: agent.Version,
System: anthropic.String("You are a helpful coding agent. Always write tests."),
})
if err != nil {
panic(err)
}
fmt.Printf("New version: %d\n", updatedAgent.Version)
// List all versions
iter := client.Beta.Agents.Versions.ListAutoPaging(ctx, agent.ID, anthropic.BetaAgentVersionListParams{})
for iter.Next() {
version := iter.Current()
fmt.Printf("Version %d: %s\n", version.Version, version.UpdatedAt.Format(time.RFC3339))
}
if err := iter.Err(); err != nil {
panic(err)
}
// Archive the agent
_, err = client.Beta.Agents.Archive(ctx, agent.ID, anthropic.BetaAgentArchiveParams{})
if err != nil {
panic(err)
}---
Send a User Message
_, err = client.Beta.Sessions.Events.Send(ctx, session.ID, anthropic.BetaSessionEventSendParams{
Events: []anthropic.SendEventsParamsUnion{{
OfUserMessage: &anthropic.BetaManagedAgentsUserMessageEventParams{
Type: anthropic.BetaManagedAgentsUserMessageEventParamsTypeUserMessage,
Content: []anthropic.BetaManagedAgentsUserMessageEventParamsContentUnion{{
OfText: &anthropic.BetaManagedAgentsTextBlockParam{
Type: anthropic.BetaManagedAgentsTextBlockTypeText,
Text: "Review the auth module",
},
}},
},
}},
})
if err != nil {
panic(err)
}💡 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.
---
Stream Events (SSE)
// Open the stream first, then send the user message
stream := client.Beta.Sessions.Events.StreamEvents(ctx, session.ID, anthropic.BetaSessionEventStreamParams{})
defer stream.Close()
if _, err := client.Beta.Sessions.Events.Send(ctx, session.ID, anthropic.BetaSessionEventSendParams{
Events: []anthropic.SendEventsParamsUnion{{
OfUserMessage: &anthropic.BetaManagedAgentsUserMessageEventParams{
Type: anthropic.BetaManagedAgentsUserMessageEventParamsTypeUserMessage,
Content: []anthropic.BetaManagedAgentsUserMessageEventParamsContentUnion{{
OfText: &anthropic.BetaManagedAgentsTextBlockParam{
Type: anthropic.BetaManagedAgentsTextBlockTypeText,
Text: "Summarize the repo README",
},
}},
},
}},
}); err != nil {
panic(err)
}
events:
for stream.Next() {
switch event := stream.Current().AsAny().(type) {
case anthropic.BetaManagedAgentsAgentMessageEvent:
for _, block := range event.Content {
fmt.Print(block.Text)
}
case anthropic.BetaManagedAgentsAgentToolUseEvent:
fmt.Printf("\n[Using tool: %s]\n", event.Name)
case anthropic.BetaManagedAgentsSessionStatusIdleEvent:
break events
case anthropic.BetaManagedAgentsSessionErrorEvent:
fmt.Printf("\n[Error: %s]\n", event.Error.Message)
break events
}
}
if err := stream.Err(); err != nil {
panic(err)
}Reconnecting and Tailing
When reconnecting mid-session, list past events first to dedupe, then tail live events:
stream := client.Beta.Sessions.Events.StreamEvents(ctx, session.ID, anthropic.BetaSessionEventStreamParams{})
defer stream.Close()
// Stream is open and buffering. List history before tailing live.
seenEventIDs := map[string]struct{}{}
history := client.Beta.Sessions.Events.ListAutoPaging(ctx, session.ID, anthropic.BetaSessionEventListParams{})
for history.Next() {
seenEventIDs[history.Current().ID] = struct{}{}
}
if err := history.Err(); err != nil {
panic(err)
}
// Tail live events, skipping anything already seen
tail:
for stream.Next() {
event := stream.Current()
if _, seen := seenEventIDs[event.ID]; seen {
continue
}
seenEventIDs[event.ID] = struct{}{}
switch event := event.AsAny().(type) {
case anthropic.BetaManagedAgentsAgentMessageEvent:
for _, block := range event.Content {
fmt.Print(block.Text)
}
case anthropic.BetaManagedAgentsSessionStatusIdleEvent:
break tail
}
}
if err := stream.Err(); err != nil {
panic(err)
}---
Provide Custom Tool Result
ℹ️ The Go managed-agents bindings foruser.custom_tool_resultare not yet documented in this skill or in the apps source examples. Refer toshared/managed-agents-events.mdfor the wire format and thegithub.com/anthropics/anthropic-sdk-gorepository for the corresponding Go params types.
---
Poll Events
// Auto-paginating iterator
iter := client.Beta.Sessions.Events.ListAutoPaging(ctx, session.ID, anthropic.BetaSessionEventListParams{})
for iter.Next() {
event := iter.Current()
fmt.Printf("%s: %s\n", event.Type, event.ID)
}
if err := iter.Err(); err != nil {
panic(err)
}---
Upload a File
csvFile, err := os.Open("data.csv")
if err != nil {
panic(err)
}
defer csvFile.Close()
file, err := client.Beta.Files.Upload(ctx, anthropic.BetaFileUploadParams{
File: csvFile,
})
if err != nil {
panic(err)
}
fmt.Printf("File ID: %s\n", file.ID)
// Mount in a session
session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
Agent: anthropic.BetaSessionNewParamsAgentUnion{
OfString: anthropic.String(agent.ID),
},
EnvironmentID: environment.ID,
Resources: []anthropic.BetaSessionNewParamsResourceUnion{{
OfFile: &anthropic.BetaManagedAgentsFileResourceParams{
Type: anthropic.BetaManagedAgentsFileResourceParamsTypeFile,
FileID: file.ID,
MountPath: anthropic.String("/workspace/data.csv"),
},
}},
})
if err != nil {
panic(err)
}Add and Manage Resources on an Existing Session
// Attach an additional file to an open session
resource, err := client.Beta.Sessions.Resources.Add(ctx, session.ID, anthropic.BetaSessionResourceAddParams{
BetaManagedAgentsFileResourceParams: anthropic.BetaManagedAgentsFileResourceParams{
Type: anthropic.BetaManagedAgentsFileResourceParamsTypeFile,
FileID: file.ID,
},
})
if err != nil {
panic(err)
}
fmt.Println(resource.ID) // "sesrsc_01ABC..."
// List resources on the session
listed, err := client.Beta.Sessions.Resources.List(ctx, session.ID, anthropic.BetaSessionResourceListParams{})
if err != nil {
panic(err)
}
for _, entry := range listed.Data {
fmt.Println(entry.ID, entry.Type)
}
// Detach a resource
if _, err := client.Beta.Sessions.Resources.Delete(ctx, resource.ID, anthropic.BetaSessionResourceDeleteParams{
SessionID: session.ID,
}); err != nil {
panic(err)
}---
List and Download Session Files
ℹ️ 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. Seeshared/managed-agents-events.mdand thegithub.com/anthropics/anthropic-sdk-gorepository for theBeta.Files.ListandBeta.Files.DownloadGo params types.
---
Session Management
// List environments
environments, err := client.Beta.Environments.List(ctx, anthropic.BetaEnvironmentListParams{})
if err != nil {
panic(err)
}
// Retrieve a specific environment
env, err := client.Beta.Environments.Get(ctx, environment.ID, anthropic.BetaEnvironmentGetParams{})
if err != nil {
panic(err)
}
// Archive an environment (read-only, existing sessions continue)
_, err = client.Beta.Environments.Archive(ctx, environment.ID, anthropic.BetaEnvironmentArchiveParams{})
if err != nil {
panic(err)
}
// Delete an environment (only if no sessions reference it)
_, err = client.Beta.Environments.Delete(ctx, environment.ID, anthropic.BetaEnvironmentDeleteParams{})
if err != nil {
panic(err)
}
// Delete a session
_, err = client.Beta.Sessions.Delete(ctx, session.ID, anthropic.BetaSessionDeleteParams{})
if err != nil {
panic(err)
}---
MCP Server Integration
// Agent declares MCP server (no auth here — auth goes in a vault)
agent, err := client.Beta.Agents.New(ctx, anthropic.BetaAgentNewParams{
Name: "GitHub Assistant",
Model: anthropic.BetaManagedAgentsModelConfigParams{
ID: "claude-opus-4-7",
Type: anthropic.BetaManagedAgentsModelConfigParamsTypeModelConfig,
},
MCPServers: []anthropic.BetaManagedAgentsUrlmcpServerParams{{
Type: anthropic.BetaManagedAgentsUrlmcpServerParamsTypeURL,
Name: "github",
URL: "https://api.githubcopilot.com/mcp/",
}},
Tools: []anthropic.BetaAgentNewParamsToolUnion{
{
OfAgentToolset20260401: &anthropic.BetaManagedAgentsAgentToolset20260401Params{
Type: anthropic.BetaManagedAgentsAgentToolset20260401ParamsTypeAgentToolset20260401,
},
},
{
OfMCPToolset: &anthropic.BetaManagedAgentsMCPToolsetParams{
Type: anthropic.BetaManagedAgentsMCPToolsetParamsTypeMCPToolset,
MCPServerName: "github",
},
},
},
})
if err != nil {
panic(err)
}
// Session attaches vault(s) containing credentials for those MCP server URLs
session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
Agent: anthropic.BetaSessionNewParamsAgentUnion{
OfBetaManagedAgentsAgents: &anthropic.BetaManagedAgentsAgentParams{
Type: anthropic.BetaManagedAgentsAgentParamsTypeAgent,
ID: agent.ID,
Version: anthropic.Int(agent.Version),
},
},
EnvironmentID: environment.ID,
VaultIDs: []string{vault.ID},
})
if err != nil {
panic(err)
}See shared/managed-agents-tools.md §Vaults for creating vaults and adding credentials.
---
Vaults
// Create a vault
vault, err := client.Beta.Vaults.New(ctx, anthropic.BetaVaultNewParams{
DisplayName: "Alice",
Metadata: map[string]string{"external_user_id": "usr_abc123"},
})
if err != nil {
panic(err)
}
// Add an OAuth credential
credential, err := client.Beta.Vaults.Credentials.New(ctx, vault.ID, anthropic.BetaVaultCredentialNewParams{
DisplayName: anthropic.String("Alice's Slack"),
Auth: anthropic.BetaVaultCredentialNewParamsAuthUnion{
OfMCPOAuth: &anthropic.BetaManagedAgentsMCPOAuthCreateParams{
Type: anthropic.BetaManagedAgentsMCPOAuthCreateParamsTypeMCPOAuth,
MCPServerURL: "https://mcp.slack.com/mcp",
AccessToken: "xoxp-...",
ExpiresAt: anthropic.Time(time.Date(2026, time.April, 15, 0, 0, 0, 0, time.UTC)),
Refresh: anthropic.BetaManagedAgentsMCPOAuthRefreshParams{
TokenEndpoint: "https://slack.com/api/oauth.v2.access",
ClientID: "1234567890.0987654321",
Scope: anthropic.String("channels:read chat:write"),
RefreshToken: "xoxe-1-...",
TokenEndpointAuth: anthropic.BetaManagedAgentsMCPOAuthRefreshParamsTokenEndpointAuthUnion{
OfClientSecretPost: &anthropic.BetaManagedAgentsTokenEndpointAuthPostParam{
Type: anthropic.BetaManagedAgentsTokenEndpointAuthPostParamTypeClientSecretPost,
ClientSecret: "abc123...",
},
},
},
},
},
})
if err != nil {
panic(err)
}
// Rotate the credential (e.g., after a token refresh)
_, err = client.Beta.Vaults.Credentials.Update(ctx, credential.ID, anthropic.BetaVaultCredentialUpdateParams{
VaultID: vault.ID,
Auth: anthropic.BetaVaultCredentialUpdateParamsAuthUnion{
OfMCPOAuth: &anthropic.BetaManagedAgentsMCPOAuthUpdateParams{
Type: anthropic.BetaManagedAgentsMCPOAuthUpdateParamsTypeMCPOAuth,
AccessToken: anthropic.String("xoxp-new-..."),
ExpiresAt: anthropic.Time(time.Date(2026, time.May, 15, 0, 0, 0, 0, time.UTC)),
Refresh: anthropic.BetaManagedAgentsMCPOAuthRefreshUpdateParams{
RefreshToken: anthropic.String("xoxe-1-new-..."),
},
},
},
})
if err != nil {
panic(err)
}
// Archive a vault
_, err = client.Beta.Vaults.Archive(ctx, vault.ID, anthropic.BetaVaultArchiveParams{})
if err != nil {
panic(err)
}---
GitHub Repository Integration
Mount a GitHub repository as a session resource (a vault holds the GitHub MCP credential):
session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
Agent: anthropic.BetaSessionNewParamsAgentUnion{OfString: anthropic.String(agent.ID)},
EnvironmentID: environment.ID,
VaultIDs: []string{vault.ID},
Resources: []anthropic.BetaSessionNewParamsResourceUnion{
{
OfGitHubRepository: &anthropic.BetaManagedAgentsGitHubRepositoryResourceParams{
Type: anthropic.BetaManagedAgentsGitHubRepositoryResourceParamsTypeGitHubRepository,
URL: "https://github.com/org/repo",
MountPath: anthropic.String("/workspace/repo"),
AuthorizationToken: "ghp_your_github_token",
},
},
},
})
if err != nil {
panic(err)
}Multiple repositories on the same session:
resources := []anthropic.BetaSessionNewParamsResourceUnion{
{
OfGitHubRepository: &anthropic.BetaManagedAgentsGitHubRepositoryResourceParams{
Type: anthropic.BetaManagedAgentsGitHubRepositoryResourceParamsTypeGitHubRepository,
URL: "https://github.com/org/frontend",
MountPath: anthropic.String("/workspace/frontend"),
AuthorizationToken: "ghp_your_github_token",
},
},
{
OfGitHubRepository: &anthropic.BetaManagedAgentsGitHubRepositoryResourceParams{
Type: anthropic.BetaManagedAgentsGitHubRepositoryResourceParamsTypeGitHubRepository,
URL: "https://github.com/org/backend",
MountPath: anthropic.String("/workspace/backend"),
AuthorizationToken: "ghp_your_github_token",
},
},
}Rotating a repository's authorization token:
listed, err := client.Beta.Sessions.Resources.List(ctx, session.ID, anthropic.BetaSessionResourceListParams{})
if err != nil {
panic(err)
}
repoResourceID := listed.Data[0].ID
_, err = client.Beta.Sessions.Resources.Update(ctx, repoResourceID, anthropic.BetaSessionResourceUpdateParams{
SessionID: session.ID,
AuthorizationToken: "ghp_your_new_github_token",
})
if err != nil {
panic(err)
}Claude API — Java
Note: The Java SDK supports the Claude API and beta tool use with annotated classes. Agent SDK is not yet available for Java.
Installation
Maven:
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java</artifactId>
<version>2.17.0</version>
</dependency>Gradle:
implementation("com.anthropic:anthropic-java:2.17.0")Client Initialization
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
// Default (reads ANTHROPIC_API_KEY from environment)
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
// Explicit API key
AnthropicClient client = AnthropicOkHttpClient.builder()
.apiKey("your-api-key")
.build();---
Basic Message Request
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_6)
.maxTokens(16000L)
.addUserMessage("What is the capital of France?")
.build();
Message response = client.messages().create(params);
response.content().stream()
.flatMap(block -> block.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text()));---
Streaming
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_6)
.maxTokens(64000L)
.addUserMessage("Write a haiku")
.build();
try (StreamResponse<RawMessageStreamEvent> streamResponse = client.messages().createStreaming(params)) {
streamResponse.stream()
.flatMap(event -> event.contentBlockDelta().stream())
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> System.out.print(textDelta.text()));
}---
Thinking
Adaptive thinking is the recommended mode for Claude 4.6+ models. Claude decides dynamically when and how much to think. The builder has a direct .thinking(ThinkingConfigAdaptive) overload — no manual union wrapping.
import com.anthropic.models.messages.ContentBlock;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.ThinkingConfigAdaptive;
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_SONNET_4_6)
.maxTokens(16000L)
.thinking(ThinkingConfigAdaptive.builder().build())
.addUserMessage("Solve this step by step: 27 * 453")
.build();
for (ContentBlock block : client.messages().create(params).content()) {
block.thinking().ifPresent(t -> System.out.println("[thinking] " + t.thinking()));
block.text().ifPresent(t -> System.out.println(t.text()));
}Deprecated:ThinkingConfigEnabled.builder().budgetTokens(N)(and the.enabledThinking(N)shortcut) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.
ContentBlock narrowing: .thinking() / .text() return Optional<T> — use .ifPresent(...) or .stream().flatMap(...). Alternative: isThinking() / asThinking() boolean+unwrap pairs (throws on wrong variant).
---
Tool Use (Beta)
The Java SDK supports beta tool use with annotated classes. Tool classes implement Supplier<String> for automatic execution via BetaToolRunner.
Tool Runner (automatic loop)
import com.anthropic.models.beta.messages.MessageCreateParams;
import com.anthropic.models.beta.messages.BetaMessage;
import com.anthropic.helpers.BetaToolRunner;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.function.Supplier;
@JsonClassDescription("Get the weather in a given location")
static class GetWeather implements Supplier<String> {
@JsonPropertyDescription("The city and state, e.g. San Francisco, CA")
public String location;
@Override
public String get() {
return "The weather in " + location + " is sunny and 72°F";
}
}
BetaToolRunner toolRunner = client.beta().messages().toolRunner(
MessageCreateParams.builder()
.model("claude-opus-4-7")
.maxTokens(16000L)
.putAdditionalHeader("anthropic-beta", "structured-outputs-2025-11-13")
.addTool(GetWeather.class)
.addUserMessage("What's the weather in San Francisco?")
.build());
for (BetaMessage message : toolRunner) {
System.out.println(message);
}Memory Tool
The Java SDK provides BetaMemoryToolHandler for implementing the memory tool backend. You supply a handler that manages file storage, and the BetaToolRunner handles memory tool calls automatically.
import com.anthropic.helpers.BetaMemoryToolHandler;
import com.anthropic.helpers.BetaToolRunner;
import com.anthropic.models.beta.messages.BetaMemoryTool20250818;
import com.anthropic.models.beta.messages.BetaMessage;
import com.anthropic.models.beta.messages.MessageCreateParams;
import com.anthropic.models.beta.messages.ToolRunnerCreateParams;
// Implement BetaMemoryToolHandler with your storage backend (e.g., filesystem)
BetaMemoryToolHandler memoryHandler = new FileSystemMemoryToolHandler(sandboxRoot);
MessageCreateParams createParams = MessageCreateParams.builder()
.model("claude-opus-4-7")
.maxTokens(4096L)
.addTool(BetaMemoryTool20250818.builder().build())
.addUserMessage("Remember that my favorite color is blue")
.build();
BetaToolRunner toolRunner = client.beta().messages().toolRunner(
ToolRunnerCreateParams.builder()
.betaMemoryToolHandler(memoryHandler)
.initialMessageParams(createParams)
.build());
for (BetaMessage message : toolRunner) {
System.out.println(message);
}See the shared memory tool concepts for more details on the memory tool.
Non-Beta Tool Declaration (manual JSON schema)
Tool.InputSchema.Properties is a freeform Map<String, JsonValue> wrapper — build property schemas via putAdditionalProperty. type: "object" is the default. The builder has a direct .addTool(Tool) overload that wraps in ToolUnion automatically.
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.Tool;
Tool tool = Tool.builder()
.name("get_weather")
.description("Get the current weather in a given location")
.inputSchema(Tool.InputSchema.builder()
.properties(Tool.InputSchema.Properties.builder()
.putAdditionalProperty("location", JsonValue.from(Map.of("type", "string")))
.build())
.required(List.of("location"))
.build())
.build();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_SONNET_4_6)
.maxTokens(16000L)
.addTool(tool)
.addUserMessage("Weather in Paris?")
.build();For manual tool loops, handle tool_use blocks in the response, send tool_result back, loop until stop_reason is "end_turn". See shared tool use concepts.
Building MessageParam with Content Blocks (Tool Result Round-Trip)
MessageParam.Content is an inner union class (string | list). Use the builder's .contentOfBlockParams(List<ContentBlockParam>) alias — there is NO separate MessageParamContent class with a static ofBlockParams:
import com.anthropic.models.messages.MessageParam;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.ToolResultBlockParam;
List<ContentBlockParam> results = List.of(
ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()
.toolUseId(toolUseBlock.id())
.content(yourResultString)
.build())
);
MessageParam toolResultMsg = MessageParam.builder()
.role(MessageParam.Role.USER)
.contentOfBlockParams(results) // builder alias for Content.ofBlockParams(...)
.build();---
Effort Parameter
Effort is nested inside OutputConfig — there is NO .effort() directly on MessageCreateParams.Builder.
import com.anthropic.models.messages.OutputConfig;
.outputConfig(OutputConfig.builder()
.effort(OutputConfig.Effort.HIGH) // or LOW, MEDIUM, MAX
.build())Combine with Thinking = ThinkingConfigAdaptive for cost-quality control.
---
Prompt Caching
System message as a list of TextBlockParam with CacheControlEphemeral. Use .systemOfTextBlockParams(...) — the plain .system(String) overload can't carry cache control. For placement patterns and the silent-invalidator audit checklist, see shared/prompt-caching.md.
import com.anthropic.models.messages.TextBlockParam;
import com.anthropic.models.messages.CacheControlEphemeral;
.systemOfTextBlockParams(List.of(
TextBlockParam.builder()
.text(longSystemPrompt)
.cacheControl(CacheControlEphemeral.builder()
.ttl(CacheControlEphemeral.Ttl.TTL_1H) // optional; also TTL_5M
.build())
.build()))There's also a top-level .cacheControl(CacheControlEphemeral) on MessageCreateParams.Builder and on Tool.builder().
Verify hits via response.usage().cacheCreationInputTokens() / response.usage().cacheReadInputTokens().
---
Token Counting
import com.anthropic.models.messages.MessageCountTokensParams;
long tokens = client.messages().countTokens(
MessageCountTokensParams.builder()
.model(Model.CLAUDE_SONNET_4_6)
.addUserMessage("Hello")
.build()
).inputTokens();---
Structured Output
The class-based overload auto-derives the JSON schema from your POJO and gives you a typed .text() return — no manual schema, no manual parsing.
import com.anthropic.models.messages.StructuredMessageCreateParams;
record Book(String title, String author) {}
record BookList(List<Book> books) {}
StructuredMessageCreateParams<BookList> params = MessageCreateParams.builder()
.model(Model.CLAUDE_SONNET_4_6)
.maxTokens(16000L)
.outputConfig(BookList.class) // returns a typed builder
.addUserMessage("List 3 classic novels")
.build();
client.messages().create(params).content().stream()
.flatMap(cb -> cb.text().stream())
.forEach(typed -> {
// typed.text() returns BookList, not String
for (Book b : typed.text().books()) System.out.println(b.title());
});Supports Jackson annotations: @JsonPropertyDescription, @JsonIgnore, @ArraySchema(minItems=...). Manual schema path: OutputConfig.builder().format(JsonOutputFormat.builder().schema(...).build()).
---
PDF / Document Input
DocumentBlockParam builder has source shortcuts. Wrap in ContentBlockParam.ofDocument() and pass via .addUserMessageOfBlockParams().
import com.anthropic.models.messages.DocumentBlockParam;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.TextBlockParam;
DocumentBlockParam doc = DocumentBlockParam.builder()
.base64Source(base64String) // or .urlSource("https://...") or .textSource("...")
.title("My Document") // optional
.build();
.addUserMessageOfBlockParams(List.of(
ContentBlockParam.ofDocument(doc),
ContentBlockParam.ofText(TextBlockParam.builder().text("Summarize this").build())))---
Server-Side Tools
Version-suffixed types; name/type auto-set by builder. Direct .addTool() overloads exist for every type — no manual ToolUnion wrapping.
import com.anthropic.models.messages.WebSearchTool20260209;
import com.anthropic.models.messages.ToolBash20250124;
import com.anthropic.models.messages.ToolTextEditor20250728;
import com.anthropic.models.messages.CodeExecutionTool20260120;
.addTool(WebSearchTool20260209.builder()
.maxUses(5L) // optional
.allowedDomains(List.of("example.com")) // optional
.build())
.addTool(ToolBash20250124.builder().build())
.addTool(ToolTextEditor20250728.builder().build())
.addTool(CodeExecutionTool20260120.builder().build())Also available: WebFetchTool20260209, MemoryTool20250818, ToolSearchToolBm25_20251119.
Beta namespace (MCP, compaction)
For beta-only features use com.anthropic.models.beta.messages.* — class names have a Beta prefix AND live in the beta package. The beta MessageCreateParams.Builder has direct .addTool(BetaToolBash20250124) overloads AND .addMcpServer():
import com.anthropic.models.beta.messages.MessageCreateParams;
import com.anthropic.models.beta.messages.BetaToolBash20250124;
import com.anthropic.models.beta.messages.BetaCodeExecutionTool20260120;
import com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition;
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_6)
.maxTokens(16000L)
.addBeta("mcp-client-2025-11-20")
.addTool(BetaToolBash20250124.builder().build())
.addTool(BetaCodeExecutionTool20260120.builder().build())
.addMcpServer(BetaRequestMcpServerUrlDefinition.builder()
.name("my-server")
.url("https://example.com/mcp")
.build())
.addUserMessage("...")
.build();
client.beta().messages().create(params);BetaTool* types are NOT interchangeable with non-beta Tool* — pick one namespace per request.
Reading server-tool blocks in the response: ServerToolUseBlock has .id(), .name() (enum), and ._input() returning raw JsonValue — there is NO typed .input(). For code execution results, unwrap two levels:
for (ContentBlock block : response.content()) {
block.serverToolUse().ifPresent(stu -> {
System.out.println("tool: " + stu.name() + " input: " + stu._input());
});
block.codeExecutionToolResult().ifPresent(r -> {
r.content().resultBlock().ifPresent(result -> {
System.out.println("stdout: " + result.stdout());
System.out.println("stderr: " + result.stderr());
System.out.println("exit: " + result.returnCode());
});
});
}---
Files API (Beta)
Under client.beta().files(). File references in messages need the beta message types (non-beta DocumentBlockParam.Source has no file-ID variant).
import com.anthropic.models.beta.files.FileUploadParams;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.messages.BetaRequestDocumentBlock;
import java.nio.file.Paths;
FileMetadata meta = client.beta().files().upload(
FileUploadParams.builder()
.file(Paths.get("/path/to/doc.pdf")) // or .file(InputStream) or .file(byte[])
.build());
// Reference in a beta message:
BetaRequestDocumentBlock doc = BetaRequestDocumentBlock.builder()
.fileSource(meta.id())
.build();Other methods: .list(), .delete(String fileId), .download(String fileId), .retrieveMetadata(String fileId).
Managed Agents — Java
Bindings not shown here: This README covers the most common managed-agents flows for Java. If you need a class, method, namespace, field, or behavior that isn't shown, WebFetch the Java 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.Agents are persistent — create once, reference by ID. Store the agent ID returned byclient.beta().agents().createand pass it to every subsequentclient.beta().sessions().create; do not callagents().createin the request path. The Anthropic CLI is one convenient way to create agents and environments from version-controlled YAML — its URL is inshared/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.
Installation
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java</artifactId>
</dependency>Client Initialization
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
// Default (uses ANTHROPIC_API_KEY env var)
var client = AnthropicOkHttpClient.fromEnv();---
Create an Environment
import com.anthropic.models.beta.environments.BetaCloudConfigParams;
import com.anthropic.models.beta.environments.EnvironmentCreateParams;
import com.anthropic.models.beta.environments.UnrestrictedNetwork;
var environment = client.beta().environments().create(EnvironmentCreateParams.builder()
.name("my-dev-env")
.config(BetaCloudConfigParams.builder()
.networking(UnrestrictedNetwork.builder().build())
.build())
.build());
System.out.println("Environment ID: " + environment.id()); // env_...---
Create an Agent (required first step)
⚠️ There is no inline agent config. Model, system, and tools live on the agent object, not the session. Always start withclient.beta().agents().create()— the session takes either.agent(agent.id())or the typedBetaManagedAgentsAgentParams.builder()...build().
Minimal
import com.anthropic.models.beta.agents.AgentCreateParams;
import com.anthropic.models.beta.agents.BetaManagedAgentsAgentToolset20260401Params;
import com.anthropic.models.beta.sessions.BetaManagedAgentsAgentParams;
import com.anthropic.models.beta.sessions.SessionCreateParams;
// 1. Create the agent (reusable, versioned)
var agent = client.beta().agents().create(AgentCreateParams.builder()
.name("Coding Assistant")
.model("claude-opus-4-7")
.system("You are a helpful coding assistant.")
.addTool(BetaManagedAgentsAgentToolset20260401Params.builder()
.type(BetaManagedAgentsAgentToolset20260401Params.Type.AGENT_TOOLSET_20260401)
.build())
.build());
// 2. Start a session
var session = client.beta().sessions().create(SessionCreateParams.builder()
.agent(BetaManagedAgentsAgentParams.builder()
.type(BetaManagedAgentsAgentParams.Type.AGENT)
.id(agent.id())
.version(agent.version())
.build())
.environmentId(environment.id())
.title("Quickstart session")
.build());
System.out.println("Session ID: " + session.id());Updating an Agent
Updates create new versions; the agent object is immutable per version.
import com.anthropic.models.beta.agents.AgentUpdateParams;
var updatedAgent = client.beta().agents().update(agent.id(), AgentUpdateParams.builder()
.version(agent.version())
.system("You are a helpful coding agent. Always write tests.")
.build());
System.out.println("New version: " + updatedAgent.version());
// List all versions
for (var version : client.beta().agents().versions().list(agent.id()).autoPager()) {
System.out.println("Version " + version.version() + ": " + version.updatedAt());
}
// Archive the agent
var archived = client.beta().agents().archive(agent.id());
System.out.println("Archived at: " + archived.archivedAt().orElseThrow());---
Send a User Message
import com.anthropic.models.beta.sessions.events.BetaManagedAgentsUserMessageEventParams;
import com.anthropic.models.beta.sessions.events.EventSendParams;
client.beta().sessions().events().send(session.id(), EventSendParams.builder()
.addEvent(BetaManagedAgentsUserMessageEventParams.builder()
.type(BetaManagedAgentsUserMessageEventParams.Type.USER_MESSAGE)
.addTextContent("Review the auth module")
.build())
.build());💡 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.
---
Stream Events (SSE)
import com.anthropic.models.beta.sessions.events.StreamEvents;
// Open the stream first, then send the user message
try (var stream = client.beta().sessions().events().streamStreaming(session.id())) {
client.beta().sessions().events().send(session.id(), EventSendParams.builder()
.addEvent(BetaManagedAgentsUserMessageEventParams.builder()
.type(BetaManagedAgentsUserMessageEventParams.Type.USER_MESSAGE)
.addTextContent("Summarize the repo README")
.build())
.build());
for (var event : (Iterable<StreamEvents>) stream.stream()::iterator) {
if (event.isAgentMessage()) {
event.asAgentMessage().content().forEach(block -> System.out.print(block.text()));
} else if (event.isAgentToolUse()) {
System.out.println("\n[Using tool: " + event.asAgentToolUse().name() + "]");
} else if (event.isSessionStatusIdle()) {
break;
} else if (event.isSessionError()) {
System.out.println("\n[Error]");
break;
}
}
}Reconnecting and Tailing
When reconnecting mid-session, list past events first to dedupe, then tail live events. The cross-variant id field is read from the raw _json() value:
import com.anthropic.core.JsonValue;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
try (var stream = client.beta().sessions().events().streamStreaming(session.id())) {
// Stream is open and buffering. List history before tailing live.
var seenEventIds = new HashSet<String>();
for (var past : client.beta().sessions().events().list(session.id()).autoPager()) {
Optional<Map<String, JsonValue>> obj = past._json().orElseThrow().asObject();
seenEventIds.add(obj.orElseThrow().get("id").asStringOrThrow());
}
// Tail live events, skipping anything already seen
for (var event : (Iterable<StreamEvents>) stream.stream()::iterator) {
Optional<Map<String, JsonValue>> obj = event._json().orElseThrow().asObject();
if (!seenEventIds.add(obj.orElseThrow().get("id").asStringOrThrow())) continue;
if (event.isAgentMessage()) {
event.asAgentMessage().content().forEach(block -> System.out.print(block.text()));
} else if (event.isSessionStatusIdle()) {
break;
}
}
}---
Provide Custom Tool Result
ℹ️ The Java managed-agents bindings foruser.custom_tool_resultare not yet documented in this skill or in the apps source examples. Refer toshared/managed-agents-events.mdfor the wire format and theanthropic-javarepository for the corresponding params types.
---
Poll Events
for (var event : client.beta().sessions().events().list(session.id()).autoPager()) {
System.out.println(event.type() + ": " + event);
}---
Upload a File
import com.anthropic.models.beta.files.FileUploadParams;
import com.anthropic.models.beta.sessions.BetaManagedAgentsFileResourceParams;
import java.nio.file.Path;
var dataCsv = Path.of("data.csv");
var file = client.beta().files().upload(FileUploadParams.builder()
.file(dataCsv)
.build());
System.out.println("File ID: " + file.id());
// Mount in a session
var session = client.beta().sessions().create(SessionCreateParams.builder()
.agent(agent.id())
.environmentId(environment.id())
.addResource(BetaManagedAgentsFileResourceParams.builder()
.type(BetaManagedAgentsFileResourceParams.Type.FILE)
.fileId(file.id())
.mountPath("/workspace/data.csv")
.build())
.build());Add and Manage Resources on an Existing Session
import com.anthropic.models.beta.sessions.resources.ResourceAddParams;
import com.anthropic.models.beta.sessions.resources.ResourceDeleteParams;
// Attach an additional file to an open session
var resource = client.beta().sessions().resources().add(session.id(), ResourceAddParams.builder()
.betaManagedAgentsFileResourceParams(BetaManagedAgentsFileResourceParams.builder()
.type(BetaManagedAgentsFileResourceParams.Type.FILE)
.fileId(file.id())
.build())
.build());
System.out.println(resource.id()); // "sesrsc_01ABC..."
// List resources on the session — entries are a discriminated union
var listed = client.beta().sessions().resources().list(session.id());
for (var entry : listed.data()) {
if (entry.isFile()) {
var fileResource = entry.asFile();
System.out.println(fileResource.id() + " " + fileResource.type());
} else if (entry.isGitHubRepository()) {
var repoResource = entry.asGitHubRepository();
System.out.println(repoResource.id() + " " + repoResource.type());
}
}
// Detach a resource
client.beta().sessions().resources().delete(resource.id(), ResourceDeleteParams.builder()
.sessionId(session.id())
.build());---
List and Download Session Files
ℹ️ Listing and downloading files an agent wrote during a session is not yet documented for Java in this skill or in the apps source examples. Seeshared/managed-agents-events.mdand theanthropic-javarepository for the file list/download bindings.
---
Session Management
// List environments
var environments = client.beta().environments().list();
// Retrieve a specific environment
var env = client.beta().environments().retrieve(environment.id());
// Archive an environment (read-only, existing sessions continue)
client.beta().environments().archive(environment.id());
// Delete an environment (only if no sessions reference it)
client.beta().environments().delete(environment.id());
// Delete a session
client.beta().sessions().delete(session.id());---
MCP Server Integration
import com.anthropic.models.beta.agents.BetaManagedAgentsMcpToolsetParams;
import com.anthropic.models.beta.agents.BetaManagedAgentsUrlmcpServerParams;
// Agent declares MCP server (no auth here — auth goes in a vault)
var agent = client.beta().agents().create(AgentCreateParams.builder()
.name("GitHub Assistant")
.model("claude-opus-4-7")
.addMcpServer(BetaManagedAgentsUrlmcpServerParams.builder()
.type(BetaManagedAgentsUrlmcpServerParams.Type.URL)
.name("github")
.url("https://api.githubcopilot.com/mcp/")
.build())
.addTool(BetaManagedAgentsAgentToolset20260401Params.builder()
.type(BetaManagedAgentsAgentToolset20260401Params.Type.AGENT_TOOLSET_20260401)
.build())
.addTool(BetaManagedAgentsMcpToolsetParams.builder()
.type(BetaManagedAgentsMcpToolsetParams.Type.MCP_TOOLSET)
.mcpServerName("github")
.build())
.build());
// Session attaches vault(s) containing credentials for those MCP server URLs
var session = client.beta().sessions().create(SessionCreateParams.builder()
.agent(BetaManagedAgentsAgentParams.builder()
.type(BetaManagedAgentsAgentParams.Type.AGENT)
.id(agent.id())
.version(agent.version())
.build())
.environmentId(environment.id())
.addVaultId(vault.id())
.build());See shared/managed-agents-tools.md §Vaults for creating vaults and adding credentials.
---
Vaults
import com.anthropic.core.JsonValue;
import com.anthropic.models.beta.vaults.VaultCreateParams;
import com.anthropic.models.beta.vaults.credentials.BetaManagedAgentsMcpOAuthCreateParams;
import com.anthropic.models.beta.vaults.credentials.BetaManagedAgentsMcpOAuthRefreshParams;
import com.anthropic.models.beta.vaults.credentials.BetaManagedAgentsMcpOAuthRefreshUpdateParams;
import com.anthropic.models.beta.vaults.credentials.BetaManagedAgentsMcpOAuthUpdateParams;
import com.anthropic.models.beta.vaults.credentials.CredentialCreateParams;
import com.anthropic.models.beta.vaults.credentials.CredentialUpdateParams;
import java.time.OffsetDateTime;
// Create a vault
var vault = client.beta().vaults().create(VaultCreateParams.builder()
.displayName("Alice")
.metadata(VaultCreateParams.Metadata.builder()
.putAdditionalProperty("external_user_id", JsonValue.from("usr_abc123"))
.build())
.build());
System.out.println(vault.id()); // "vlt_01ABC..."
// Add an OAuth credential
var credential = client.beta().vaults().credentials().create(vault.id(),
CredentialCreateParams.builder()
.displayName("Alice's Slack")
.auth(BetaManagedAgentsMcpOAuthCreateParams.builder()
.type(BetaManagedAgentsMcpOAuthCreateParams.Type.MCP_OAUTH)
.mcpServerUrl("https://mcp.slack.com/mcp")
.accessToken("xoxp-...")
.expiresAt(OffsetDateTime.parse("2026-04-15T00:00:00Z"))
.refresh(BetaManagedAgentsMcpOAuthRefreshParams.builder()
.tokenEndpoint("https://slack.com/api/oauth.v2.access")
.clientId("1234567890.0987654321")
.scope("channels:read chat:write")
.refreshToken("xoxe-1-...")
.clientSecretPostTokenEndpointAuth("abc123...")
.build())
.build())
.build());
// Rotate the credential (e.g., after a token refresh)
client.beta().vaults().credentials().update(credential.id(),
CredentialUpdateParams.builder()
.vaultId(vault.id())
.auth(BetaManagedAgentsMcpOAuthUpdateParams.builder()
.type(BetaManagedAgentsMcpOAuthUpdateParams.Type.MCP_OAUTH)
.accessToken("xoxp-new-...")
.expiresAt(OffsetDateTime.parse("2026-05-15T00:00:00Z"))
.refresh(BetaManagedAgentsMcpOAuthRefreshUpdateParams.builder()
.refreshToken("xoxe-1-new-...")
.build())
.build())
.build());
// Archive a vault
client.beta().vaults().archive(vault.id());---
GitHub Repository Integration
Mount a GitHub repository as a session resource (a vault holds the GitHub MCP credential):
import com.anthropic.models.beta.sessions.BetaManagedAgentsGitHubRepositoryResourceParams;
var session = client.beta().sessions().create(SessionCreateParams.builder()
.agent(agent.id())
.environmentId(environment.id())
.addVaultId(vault.id())
.addResource(BetaManagedAgentsGitHubRepositoryResourceParams.builder()
.type(BetaManagedAgentsGitHubRepositoryResourceParams.Type.GITHUB_REPOSITORY)
.url("https://github.com/org/repo")
.mountPath("/workspace/repo")
.authorizationToken("ghp_your_github_token")
.build())
.build());Multiple repositories on the same session:
import java.util.List;
var resources = List.of(
BetaManagedAgentsGitHubRepositoryResourceParams.builder()
.type(BetaManagedAgentsGitHubRepositoryResourceParams.Type.GITHUB_REPOSITORY)
.url("https://github.com/org/frontend")
.mountPath("/workspace/frontend")
.authorizationToken("ghp_your_github_token")
.build(),
BetaManagedAgentsGitHubRepositoryResourceParams.builder()
.type(BetaManagedAgentsGitHubRepositoryResourceParams.Type.GITHUB_REPOSITORY)
.url("https://github.com/org/backend")
.mountPath("/workspace/backend")
.authorizationToken("ghp_your_github_token")
.build());Rotating a repository's authorization token:
import com.anthropic.models.beta.sessions.resources.ResourceUpdateParams;
var listed = client.beta().sessions().resources().list(session.id());
var repoResourceId = listed.data().get(0).asGitHubRepository().id();
client.beta().sessions().resources().update(repoResourceId, ResourceUpdateParams.builder()
.sessionId(session.id())
.authorizationToken("ghp_your_new_github_token")
.build());Message Batches API — Python
The Batches API (POST /v1/messages/batches) processes Messages API requests asynchronously at 50% of standard prices.
Key Facts
- Up to 100,000 requests or 256 MB per batch
- Most batches complete within 1 hour; maximum 24 hours
- Results available for 29 days after creation
- 50% cost reduction on all token usage
- All Messages API features supported (vision, tools, caching, etc.)
---
Create a Batch
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
message_batch = client.messages.batches.create(
requests=[
Request(
custom_id="request-1",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{"role": "user", "content": "Summarize climate change impacts"}]
)
),
Request(
custom_id="request-2",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{"role": "user", "content": "Explain quantum computing basics"}]
)
),
]
)
print(f"Batch ID: {message_batch.id}")
print(f"Status: {message_batch.processing_status}")---
Poll for Completion
import time
while True:
batch = client.messages.batches.retrieve(message_batch.id)
if batch.processing_status == "ended":
break
print(f"Status: {batch.processing_status}, processing: {batch.request_counts.processing}")
time.sleep(60)
print("Batch complete!")
print(f"Succeeded: {batch.request_counts.succeeded}")
print(f"Errored: {batch.request_counts.errored}")---
Retrieve Results
Note: Examples below usematch/casesyntax, requiring Python 3.10+. For earlier versions, useif/elifchains instead.
for result in client.messages.batches.results(message_batch.id):
match result.result.type:
case "succeeded":
msg = result.result.message
text = next((b.text for b in msg.content if b.type == "text"), "")
print(f"[{result.custom_id}] {text[:100]}")
case "errored":
if result.result.error.type == "invalid_request":
print(f"[{result.custom_id}] Validation error - fix request and retry")
else:
print(f"[{result.custom_id}] Server error - safe to retry")
case "canceled":
print(f"[{result.custom_id}] Canceled")
case "expired":
print(f"[{result.custom_id}] Expired - resubmit")---
Cancel a Batch
cancelled = client.messages.batches.cancel(message_batch.id)
print(f"Status: {cancelled.processing_status}") # "canceling"---
Batch with Prompt Caching
shared_system = [
{"type": "text", "text": "You are a literary analyst."},
{
"type": "text",
"text": large_document_text, # Shared across all requests
"cache_control": {"type": "ephemeral"}
}
]
message_batch = client.messages.batches.create(
requests=[
Request(
custom_id=f"analysis-{i}",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-7",
max_tokens=16000,
system=shared_system,
messages=[{"role": "user", "content": question}]
)
)
for i, question in enumerate(questions)
]
)---
Full End-to-End Example
import anthropic
import time
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
# 1. Prepare requests
items_to_classify = [
"The product quality is excellent!",
"Terrible customer service, never again.",
"It's okay, nothing special.",
]
requests = [
Request(
custom_id=f"classify-{i}",
params=MessageCreateParamsNonStreaming(
model="claude-haiku-4-5",
max_tokens=50,
messages=[{
"role": "user",
"content": f"Classify as positive/negative/neutral (one word): {text}"
}]
)
)
for i, text in enumerate(items_to_classify)
]
# 2. Create batch
batch = client.messages.batches.create(requests=requests)
print(f"Created batch: {batch.id}")
# 3. Wait for completion
while True:
batch = client.messages.batches.retrieve(batch.id)
if batch.processing_status == "ended":
break
time.sleep(10)
# 4. Collect results
results = {}
for result in client.messages.batches.results(batch.id):
if result.result.type == "succeeded":
msg = result.result.message
results[result.custom_id] = next((b.text for b in msg.content if b.type == "text"), "")
for custom_id, classification in sorted(results.items()):
print(f"{custom_id}: {classification}")