32 ファイル変更+421-250

この更新の概要

Agent SDKにおけるPythonコード例がasyncio.run(main())を含む実行可能な形式に刷新され、プログラム実装の具体性が向上しました。MCP接続時のブロッキング制御を可能にするMCP_CONNECTION_NONBLOCKING環境変数の解説が追加され、サーバー接続待ちの挙動を調整できるようになっています。セッション管理においてステートレスな環境やサーバーレス環境での永続化を実現するSessionStoreアダプターとCLAUDE_CONFIG_DIRの設定方法が詳細化されました。その他、Amazon Bedrock利用時の認証要件や、ツール実行時の構造化データ処理に関する補足説明が各ドキュメントに反映されています。

agent-sdk/agent-loop+4-3

エージェントループにおける可観測性イベントの定義を整理し、SessionStoreアダプターを用いたステートレス環境でのセッション再開手順が追加されました。

@@ -59,7 +59,7 @@ As the loop runs, the SDK yields a stream of messages. Each message carries a ty
- **`StreamEvent`:** only emitted when partial messages are enabled. Contains raw API streaming events (text deltas, tool input chunks). See [Stream responses](/en/agent-sdk/streaming-output).
- **`ResultMessage`:** marks the end of the agent loop. Contains the final text result, token usage, cost, and session ID. Check the `subtype` field to determine whether the task succeeded or hit a limit. A small number of trailing system events, such as `prompt_suggestion`, can arrive after it, so iterate the stream to completion rather than breaking on the result. See [Handle the result](#handle-the-result).
These five types cover the full agent loop lifecycle in both SDKs. The TypeScript SDK also yields additional observability events (hook events, tool progress, rate limits, task notifications) that provide extra detail but are not required to drive the loop. See the [Python message types reference](/en/agent-sdk/python#message-types) and [TypeScript message types reference](/en/agent-sdk/typescript#message-types) for the complete lists.
These five types cover the full agent loop lifecycle. Both SDKs also yield observability events such as rate-limit status and task notifications that are not required to drive the loop. See the [Python message types reference](/en/agent-sdk/python#message-types) and [TypeScript message types reference](/en/agent-sdk/typescript#message-types) for the complete lists.
### Handle messages
@@ -216,7 +216,7 @@ If you don't set `model`, the SDK uses Claude Code's default, which depends on y
## The context window
The context window is the total amount of information available to Claude during a session. It does not reset between turns within a session. Everything accumulates: the system prompt, tool definitions, conversation history, tool inputs, and tool outputs. Content that stays the same across turns (system prompt, tool definitions, CLAUDE.md) is automatically [prompt cached](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), which reduces cost and latency for repeated prefixes.
The context window is the total amount of information available to Claude during a session. It does not reset between turns within a session. Everything accumulates: the system prompt, tool definitions, conversation history, tool inputs, and tool outputs. Content that stays the same across turns (system prompt, tool definitions, CLAUDE.md) is automatically [prompt cached](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), which reduces cost and latency for repeated prefixes. For how a custom system prompt or `append` text affects cache reuse across sessions, see [Modifying system prompts](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines).
### What consumes context
@@ -273,7 +273,7 @@ Each interaction with the SDK creates or continues a session. Capture the sessio
When you resume, the full context from previous turns is restored: files that were read, analysis that was performed, and actions that were taken. You can also fork a session to branch into a different approach without modifying the original.
See [Session management](/en/agent-sdk/sessions) for the full guide on resume, continue, and fork patterns.
See [Session management](/en/agent-sdk/sessions) for the full guide on resume, continue, and fork patterns. To resume sessions across stateless containers or serverless hosts, pass a [`session_store` / `sessionStore` adapter](/en/agent-sdk/session-storage) so transcripts are mirrored to your own backend and any host can resume them. The Claude Code subprocess still writes to local disk first; point `CLAUDE_CONFIG_DIR` at a temp directory in `options.env` if the local copy needs to be ephemeral.
In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claudesdkclient) for details.
@@ -422,5 +422,6 @@ Now that you understand the loop, here's where to go depending on what you're bu
- **Building an interactive UI?** Enable [streaming](/en/agent-sdk/streaming-output) to show live text and tool calls as the loop runs.
- **Need tighter control over what the agent can do?** Lock down tool access with [permissions](/en/agent-sdk/permissions), and use [hooks](/en/agent-sdk/hooks) to audit, block, or transform tool calls before they execute.
- **Running long or expensive tasks?** Offload isolated work to [subagents](/en/agent-sdk/subagents) to keep your main context lean.
- **Deploying as a service?** See [Hosting the Agent SDK](/en/agent-sdk/hosting) for container and serverless guidance, and [Session storage](/en/agent-sdk/session-storage) to persist sessions to your own backend.
For the broader conceptual picture of the agentic loop (not SDK-specific), see [How Claude Code works](/en/how-claude-code-works). For a practical guide to designing loops in Claude Code, from turn-based to goal-based and proactive loops, see [Loop engineering: getting started with loops](https://claude.com/blog/getting-started-with-loops) on the blog.
agent-sdk/claude-code-features+56-42

Pythonのコード例がより実用的な構造に更新され、フックのコールバック引数でエージェントIDを識別する方法が明記されました。

@@ -21,23 +21,27 @@ This example loads both user-level and project-level settings by setting `settin
```python Python theme={null}
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async for message in query(
prompt="Help me refactor the auth module",
options=ClaudeAgentOptions(
# "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.
# Together they give the agent access to CLAUDE.md, skills, hooks, and
# permissions from both locations.
setting_sources=["user", "project"],
allowed_tools=["Read", "Edit", "Bash"],
),
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text)
if isinstance(message, ResultMessage) and message.subtype == "success":
print(f"\nResult: {message.result}")
import asyncio
async def main():
async for message in query(
prompt="Help me refactor the auth module",
options=ClaudeAgentOptions(
# "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.
# Together they give the agent access to CLAUDE.md, skills, hooks, and
# permissions from both locations.
setting_sources=["user", "project"],
allowed_tools=["Read", "Edit", "Bash"],
),
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text)
if isinstance(message, ResultMessage) and message.subtype == "success":
print(f"\nResult: {message.result}")
asyncio.run(main())
```
```typescript TypeScript theme={null}
@@ -64,6 +68,8 @@ for await (const message of query({
}
```
When this runs, the assistant's response prints to stdout, followed by a final result line once the run completes.
Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option, or the process's current directory if unset. For the full type definition, see [`SettingSource`](/en/agent-sdk/typescript#settingsource) (TypeScript) or [`SettingSource`](/en/agent-sdk/python#settingsource) (Python).
| Source | What it loads | Location |
@@ -119,19 +125,23 @@ Skills are discovered from the filesystem through `settingSources`. When the `sk
```python Python theme={null}
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
import asyncio
# Skills in .claude/skills/ are discovered automatically
# when settingSources includes "project"
async for message in query(
prompt="Review this PR using our code review checklist",
options=ClaudeAgentOptions(
setting_sources=["user", "project"],
skills="all",
allowed_tools=["Read", "Grep", "Glob"],
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
async def main():
async for message in query(
prompt="Review this PR using our code review checklist",
options=ClaudeAgentOptions(
setting_sources=["user", "project"],
skills="all",
allowed_tools=["Read", "Grep", "Glob"],
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
```
```typescript TypeScript theme={null}
@@ -170,11 +180,12 @@ Hook callbacks receive the tool input and return a decision dict. Returning `{}`
```python Python theme={null}
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, ResultMessage
import asyncio
# PreToolUse hook callback. Positional args:
# input_data: HookInput dict with tool_name, tool_input, hook_event_name
# tool_use_id: str | None, the ID of the tool call being intercepted
# context: HookContext, carries session metadata
# context: HookContext, reserved for future abort-signal support
async def audit_bash(input_data, tool_use_id, context):
command = input_data.get("tool_input", {}).get("command", "")
if "rm -rf" in command:
@@ -189,19 +200,22 @@ async def audit_bash(input_data, tool_use_id, context):
# Filesystem hooks from .claude/settings.json run automatically
# when settingSources loads them. You can also add programmatic hooks:
async for message in query(
prompt="Refactor the auth module",
options=ClaudeAgentOptions(
setting_sources=["project"], # Loads hooks from .claude/settings.json
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[audit_bash]),
]
},
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
async def main():
async for message in query(
prompt="Refactor the auth module",
options=ClaudeAgentOptions(
setting_sources=["project"], # Loads hooks from .claude/settings.json
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[audit_bash]),
]
},
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
```
```typescript TypeScript theme={null}
@@ -247,7 +261,7 @@ for await (const message of query({
| Hook type | Best for |
| :- | :- |
| **Filesystem** (`settings.json`) | Sharing hooks between CLI and SDK sessions. Supports `"command"` (shell scripts), `"http"` (POST to an endpoint), `"mcp_tool"` (call a connected MCP server's tool), `"prompt"` (LLM evaluates a prompt), and `"agent"` (spawns a verifier agent). These fire in the main agent and any subagents it spawns. |
| **Programmatic** (callbacks in `query()`) | Application-specific logic, structured decisions, and in-process integration. These also fire inside subagents. The callback receives `agent_id` and `agent_type` to distinguish. |
| **Programmatic** (callbacks in `query()`) | Application-specific logic, structured decisions, and in-process integration. These also fire inside subagents. The hook input, the callback's first argument, carries `agent_id` and `agent_type` fields that identify which agent fired the hook. |
The TypeScript SDK supports additional hook events beyond Python, including `SessionStart`, `SessionEnd`, `TeammateIdle`, and `TaskCompleted`. See the [hooks guide](/en/agent-sdk/hooks) for the full event compatibility table.
agent-sdk/cost-tracking+1-1

Amazon Bedrockを使用する際のTTL設定例において、有効なAWS認証情報が必要である旨の注意書きが追加されました。

@@ -263,7 +263,7 @@ Cache entries written by the SDK use a 5-minute TTL by default when you authenti
To request a 1-hour TTL on cache writes, set the [`ENABLE_PROMPT_CACHING_1H`](/en/env-vars) environment variable. You can export it in your shell or container environment, or pass it through `options.env`.
The following example enables 1-hour TTL for an agent running on Amazon Bedrock:
The following example enables 1-hour TTL for an agent running on Amazon Bedrock. Because it sets `CLAUDE_CODE_USE_BEDROCK`, it requires working AWS credentials for [Amazon Bedrock](/en/amazon-bedrock); without them the query fails.
```python Python theme={null}
from claude_agent_sdk import ClaudeAgentOptions, query
agent-sdk/custom-tools+1-1

カスタムツールでstructuredContentを使用する際、テキストブロックが除外される仕様とバイナリデータの扱いについて補足されました。

@@ -535,7 +535,7 @@ These block shapes come from the MCP `CallToolResult` type. See the [MCP specifi
`structuredContent` is an optional JSON object on the result, separate from the `content` array. Use it to return raw values that Claude can read as exact fields instead of parsing them out of a text string or image.
When `structuredContent` is set, Claude receives the JSON plus any image or resource blocks from `content`. Text blocks in `content` are not forwarded, since they are assumed to duplicate the structured data. The example below renders a chart as an image block and returns the data points behind it in `structuredContent` from the same handler.
When `structuredContent` is set, Claude receives the JSON plus any image or resource blocks from `content`. Text blocks in `content` are not forwarded, since they are assumed to duplicate the structured data. The example below renders a chart as an image block and returns the data points behind it in `structuredContent` from the same handler. In the snippet, `chartPngBuffer` is a `Buffer` holding the rendered PNG bytes.
```typescript TypeScript
return {
agent-sdk/hosting+39-23

ホスティング環境向けのコードサンプルがasync/awaitの適切な構造に更新され、SessionStoreのインポート手順が示されました。

@@ -98,16 +98,24 @@ for await (const message of query({
```
```python Python theme={null}
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt=user_input,
options=ClaudeAgentOptions(
resume=session_id, # looked up from your database by user
session_store=session_store, # S3, Redis, Postgres, or your own adapter
),
):
...
from claude_agent_sdk import query, ClaudeAgentOptions, SessionStore
import asyncio
user_input: str = ...
session_id: str = ... # looked up from your database by user
session_store: SessionStore = ... # S3, Redis, Postgres, or your own adapter
async def main():
async for message in query(
prompt=user_input,
options=ClaudeAgentOptions(
resume=session_id,
session_store=session_store,
),
):
...
asyncio.run(main())
```
See [Session storage](/en/agent-sdk/session-storage) for the full `SessionStore` interface and reference adapters.
@@ -261,19 +269,27 @@ for await (const message of query({
```python Python theme={null}
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt=prompt,
options=ClaudeAgentOptions(
cwd=tenant_dir,
setting_sources=[],
env={
"CLAUDE_CONFIG_DIR": config_dir,
"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1",
},
),
):
...
import asyncio
prompt: str = ...
tenant_dir: str = ...
config_dir: str = ...
async def main():
async for message in query(
prompt=prompt,
options=ClaudeAgentOptions(
cwd=tenant_dir,
setting_sources=[],
env={
"CLAUDE_CONFIG_DIR": config_dir,
"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1",
},
),
):
...
asyncio.run(main())
```
For per-tenant network controls, see [Secure Deployment](/en/agent-sdk/secure-deployment).
agent-sdk/mcp+118-57

PythonでのMCPサーバー設定例が追加されるとともに、環境変数による接続ブロッキング制御とツール名の命名規則が説明されています。

@@ -147,7 +147,7 @@ MCP tools follow the naming pattern `mcp__<server-name>__<tool-name>`. For examp
Use `allowedTools` to auto-approve specific MCP tools so Claude can use them without a permission prompt:
```typescript hidelines={1,-1} theme={null}
```typescript TypeScript hidelines={1,-1} theme={null}
const _ = {
options: {
mcpServers: {
@@ -162,39 +162,77 @@ const _ = {
};
```
```python Python theme={null}
options = ClaudeAgentOptions(
mcp_servers={
# your servers
},
allowed_tools=[
"mcp__github__*", # All tools from the github server
"mcp__db__query", # Only the query tool from db server
"mcp__slack__send_message", # Only send_message from slack server
],
)
```
Wildcards (`*`) let you allow all tools from a server without listing each one individually.
**Prefer `allowedTools` over permission modes for MCP access.** `permissionMode: "acceptEdits"` does not auto-approve MCP tools (only file edits and filesystem Bash commands). `permissionMode: "bypassPermissions"` does auto-approve MCP tools but also disables most other safety prompts, which is broader than necessary; see [How permissions are evaluated](/en/agent-sdk/permissions#how-permissions-are-evaluated) for the prompts that remain. A wildcard in `allowedTools` grants exactly the MCP server you want and nothing more. See [Permission modes](/en/agent-sdk/permissions#permission-modes) for a full comparison.
### Discover available tools
To see what tools an MCP server provides, check the server's documentation or connect to the server and inspect the `system` init message:
To see what tools an MCP server provides, check the server's documentation or inspect the `tools` array in the `system` init message. MCP tool names start with `mcp__`.
MCP servers connect in the background by default, so the init message arrives before they finish: the `tools` array lists only built-in tools and `mcp_servers` shows a `pending` status for each server. Set the [`MCP_CONNECTION_NONBLOCKING`](/en/env-vars) environment variable to `0` to wait up to 5 seconds for servers to connect before the init message is sent; servers that connect in time list their `mcp__` tools there, and slower ones keep connecting in the background:
```bash
export MCP_CONNECTION_NONBLOCKING=0
```
With that variable set, this filter prints the MCP tool names:
```typescript TypeScript theme={null}
import { query } from "@anthropic-ai/claude-agent-sdk";
const options = {
mcpServers: {
// your servers
},
};
for await (const message of query({ prompt: "...", options })) {
if (message.type === "system" && message.subtype === "init") {
console.log("Available MCP tools:", message.mcp_servers);
const mcpTools = message.tools.filter((name) => name.startsWith("mcp__"));
console.log("Available MCP tools:", mcpTools);
}
}
```
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, SystemMessage
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
# your servers
},
)
async for message in query(prompt="...", options=options):
if isinstance(message, SystemMessage) and message.subtype == "init":
print("Available MCP tools:", message.data["mcp_servers"])
mcp_tools = [t for t in message.data.get("tools", []) if t.startswith("mcp__")]
print("Available MCP tools:", mcp_tools)
asyncio.run(main())
```
You can also ask Claude to list the tools available from a server.
## Transport types
MCP servers communicate with your agent using different transport protocols. Check the server's documentation to see which transport it supports:
- If the docs give you a **command to run** (like `npx @modelcontextprotocol/server-github`), use stdio
- If the docs give you a **command to run** (like `npx @modelcontextprotocol/server-filesystem`), use stdio
- If the docs give you a **URL**, use HTTP or SSE
- If you're building your own tools in code, use an SDK MCP server
@@ -206,15 +244,12 @@ Local processes that communicate via stdin/stdout. Use this for MCP servers you
const _ = {
options: {
mcpServers: {
github: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
},
allowedTools: ["mcp__github__list_issues", "mcp__github__search_issues"]
allowedTools: ["mcp__filesystem__read_file", "mcp__filesystem__list_directory"]
}
};
```
@@ -222,25 +257,25 @@ const _ = {
```python Python theme={null}
options = ClaudeAgentOptions(
mcp_servers={
"github": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/me/projects",
],
}
},
allowed_tools=["mcp__github__list_issues", "mcp__github__search_issues"],
allowed_tools=["mcp__filesystem__read_file", "mcp__filesystem__list_directory"],
)
```
```json theme={null}
{
"mcpServers": {
"github": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
}
}
@@ -306,9 +341,7 @@ An SDK MCP server registered by an [`initialize` control request](/en/agent-sdk/
When you have many MCP tools configured, tool definitions can consume a significant portion of your context window. Tool search solves this by withholding tool definitions from context and loading only the ones Claude needs for each turn.
Tool search is enabled by default. See [Tool search](/en/agent-sdk/tool-search) for configuration options and details.
For more detail, including best practices and using tool search with custom SDK tools, see the [tool search guide](/en/agent-sdk/tool-search).
Tool search is enabled by default. See [Tool search](/en/agent-sdk/tool-search) for configuration options, best practices, and using tool search with custom SDK tools.
## Authentication
@@ -322,15 +355,15 @@ Use the `env` field to pass API keys, tokens, and other credentials to the MCP s
const _ = {
options: {
mcpServers: {
github: {
"api-server": {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
args: ["-y", "@your-org/api-mcp-server"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
API_KEY: process.env.API_KEY
}
}
},
allowedTools: ["mcp__github__list_issues"]
allowedTools: ["mcp__api-server__*"]
}
};
```
@@ -338,33 +371,31 @@ const _ = {
```python Python theme={null}
options = ClaudeAgentOptions(
mcp_servers={
"github": {
"api-server": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
"args": ["-y", "@your-org/api-mcp-server"],
"env": {"API_KEY": os.environ["API_KEY"]},
}
},
allowed_tools=["mcp__github__list_issues"],
allowed_tools=["mcp__api-server__*"],
)
```
```json theme={null}
{
"mcpServers": {
"github": {
"api-server": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"args": ["-y", "@your-org/api-mcp-server"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
"API_KEY": "${API_KEY}"
}
}
}
}
```
The `${GITHUB_TOKEN}` syntax expands environment variables at runtime.
See [List issues from a repository](#list-issues-from-a-repository) for a complete working example with debug logging.
The `${API_KEY}` syntax expands environment variables at runtime.
### HTTP headers for remote servers
@@ -416,14 +447,17 @@ options = ClaudeAgentOptions(
The `${API_TOKEN}` syntax expands environment variables at runtime.
For a complete working example of a remote server authenticated with headers, see [List issues from a repository](#list-issues-from-a-repository).
### OAuth2 authentication
The [MCP specification supports OAuth 2.1](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) for authorization. The SDK doesn't open a browser or run an interactive OAuth flow. When a configured server returns an authorization challenge and no stored token is available, the agent run continues without that server's tools, and the server is reported with status `needs-auth` in the `mcp_servers` array of the [system init message](/en/agent-sdk/typescript#sdksystemmessage). Check that array at startup if your agent depends on a specific server being connected.
The [MCP specification supports OAuth 2.1](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) for authorization. The SDK doesn't open a browser or run an interactive OAuth flow. When a configured server returns an authorization challenge and no stored token is available, the agent run continues without that server's tools, and the server reports status `needs-auth`. Because servers connect in the background by default, the `mcp_servers` array of the [system init message](/en/agent-sdk/typescript#sdksystemmessage) may still show `pending` for that server. To confirm whether a server needs credentials, poll `mcpServerStatus()` in the TypeScript SDK or [`get_mcp_status()`](/en/agent-sdk/python#methods) in Python, or set `MCP_CONNECTION_NONBLOCKING=0` to wait for connections before the init message.
To supply credentials, complete the OAuth flow in your own application and pass the resulting access token in the server's `headers`:
```typescript TypeScript theme={null}
// After completing OAuth flow in your app
// After completing OAuth flow in your app.
// Implement getAccessTokenFromOAuthFlow for your OAuth provider.
const accessToken = await getAccessTokenFromOAuthFlow();
const options = {
@@ -441,7 +475,8 @@ const options = {
```
```python Python theme={null}
# After completing OAuth flow in your app
# After completing OAuth flow in your app.
# Implement get_access_token_from_oauth_flow for your OAuth provider.
access_token = await get_access_token_from_oauth_flow()
options = ClaudeAgentOptions(
@@ -460,12 +495,12 @@ options = ClaudeAgentOptions(
### List issues from a repository
This example connects to the [GitHub MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/github) to list recent issues. The example includes debug logging to verify the MCP connection and tool calls.
This example connects to the remote [GitHub MCP server](https://github.com/github/github-mcp-server) to list recent issues. The example includes debug logging to verify the MCP connection and tool calls.
Before running, create a [GitHub personal access token](https://github.com/settings/tokens) with `repo` scope and set it as an environment variable:
Before running, create a [GitHub personal access token](https://github.com/settings/personal-access-tokens) with read access to the repositories you want to query and set it as an environment variable:
```bash
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx
export GITHUB_TOKEN=YOUR_GITHUB_PAT
```
```typescript TypeScript theme={null}
@@ -476,10 +511,10 @@ for await (const message of query({
options: {
mcpServers: {
github: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
type: "http",
url: "https://api.githubcopilot.com/mcp/",
headers: {
Authorization: `Bearer ${process.env.GITHUB_TOKEN}`
}
}
},
@@ -522,9 +557,9 @@ async def main():
options = ClaudeAgentOptions(
mcp_servers={
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"headers": {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"},
}
},
allowed_tools=["mcp__github__list_issues"],
@@ -553,7 +588,13 @@ asyncio.run(main())
### Query a database
This example uses the [Postgres MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres) to query a database. The connection string is passed as an argument to the server. The agent automatically discovers the database schema, writes the SQL query, and returns the results:
This example uses the [Postgres MCP server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres) to query a database. The reference server is archived but still runs with `npx`. The connection string is passed as an argument to the server. The agent automatically discovers the database schema, writes the SQL query, and returns the results.
Before running, set the `DATABASE_URL` environment variable to your connection string. Replace the placeholder values with your own database details:
```bash
export DATABASE_URL=postgresql://user:password@localhost:5432/mydb
```
```typescript TypeScript theme={null}
import { query } from "@anthropic-ai/claude-agent-sdk";
@@ -622,7 +663,7 @@ asyncio.run(main())
MCP servers can fail to connect for various reasons: the server process might not be installed, credentials might be invalid, or a remote server might be unreachable.
The SDK emits a `system` message with subtype `init` at the start of each query. This message includes the connection status for each MCP server. Check the `status` field to detect connection failures before the agent starts working:
The SDK emits a `system` message with subtype `init` at the start of each query. This message includes the connection status for each MCP server. The `status` field can be `"pending"`, `"connected"`, `"failed"`, `"needs-auth"`, or `"disabled"`. Servers connect in the background, so healthy servers often still report `"pending"` when the init message is emitted. Check for `"failed"` to detect servers that could not connect, and don't treat `"pending"` as a failure:
```typescript TypeScript theme={null}
import { query } from "@anthropic-ai/claude-agent-sdk";
@@ -631,12 +672,13 @@ for await (const message of query({
prompt: "Process data",
options: {
mcpServers: {
// Replace dataServer with your server configuration
"data-processor": dataServer
}
}
})) {
if (message.type === "system" && message.subtype === "init") {
const failedServers = message.mcp_servers.filter((s) => s.status !== "connected");
const failedServers = message.mcp_servers.filter((s) => s.status === "failed");
if (failedServers.length > 0) {
console.warn("Failed to connect:", failedServers);
@@ -654,6 +696,7 @@ import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage
async def main():
# Replace data_server with your server configuration
options = ClaudeAgentOptions(mcp_servers={"data-processor": data_server})
async for message in query(prompt="Process data", options=options):
@@ -661,7 +704,7 @@ async def main():
failed_servers = [
s
for s in message.data.get("mcp_servers", [])
if s.get("status") != "connected"
if s.get("status") == "failed"
]
if failed_servers:
@@ -682,7 +725,7 @@ asyncio.run(main())
Check the `init` message to see which servers failed to connect:
```typescript
```typescript TypeScript theme={null}
if (message.type === "system" && message.subtype === "init") {
for (const server of message.mcp_servers) {
if (server.status === "failed") {
@@ -692,6 +735,15 @@ if (message.type === "system" && message.subtype === "init") {
}
```
```python Python theme={null}
if isinstance(message, SystemMessage) and message.subtype == "init":
for server in message.data.get("mcp_servers", []):
if server.get("status") == "failed":
print(f"Server {server['name']} failed to connect")
```
A `"pending"` status means the server is still connecting, not that it failed. To get updated statuses later in the session, call the query's `mcpServerStatus()` method in the TypeScript SDK, or [`ClaudeSDKClient.get_mcp_status()`](/en/agent-sdk/python#methods) in Python.
Common causes:
- **Missing environment variables**: Ensure required tokens and credentials are set. For stdio servers, check the `env` field matches what the server expects.
@@ -703,7 +755,7 @@ Common causes:
If Claude sees tools but doesn't use them, check that you've granted permission with `allowedTools`:
```typescript hidelines={1,-1} theme={null}
```typescript TypeScript hidelines={1,-1} theme={null}
const _ = {
options: {
mcpServers: {
@@ -714,6 +766,15 @@ const _ = {
};
```
```python Python theme={null}
options = ClaudeAgentOptions(
mcp_servers={
# your servers
},
allowed_tools=["mcp__servername__*"], # Auto-approve calls from this server
)
```
### Connection timeouts
MCP server connections time out after 30 seconds by default. If your server takes longer to start, the connection fails. Raise the limit with the [`MCP_TIMEOUT`](/en/env-vars) environment variable, in milliseconds. For servers that need more startup time, also consider:
agent-sdk/migration-guide+48-38

SDKの変更に伴う移行手順が更新され、新しいAPI構造に合わせたコードの書き換え方法が詳しく記述されています。

@@ -68,7 +68,7 @@ After:
```json
{
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.0"
"@anthropic-ai/claude-agent-sdk": "^0.3.0"
}
}
```
@@ -82,9 +82,11 @@ Make any code changes needed to complete the migration.
**1. Uninstall the old package:**
```bash
pip uninstall claude-code-sdk
pip uninstall -y claude-code-sdk
```
If the old package isn't installed, pip prints `WARNING: Skipping claude-code-sdk as it is not installed.` That's expected and you can continue to the next step.
**2. Install the new package:**
```bash
@@ -178,28 +180,32 @@ const customResult = query({
```
```python Python theme={null}
# BEFORE (v0.0.x) - Used Claude Code's system prompt by default
async for message in query(prompt="Hello"):
print(message)
# AFTER (v0.1.0) - Uses minimal system prompt by default
# To get the old behavior, explicitly request Claude Code's preset:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
system_prompt={"type": "preset", "preset": "claude_code"} # Use the preset
),
):
print(message)
# Or use a custom system prompt:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(system_prompt="You are a helpful coding assistant"),
):
print(message)
import asyncio
async def main():
# BEFORE (v0.0.x) - Used Claude Code's system prompt by default
async for message in query(prompt="Hello"):
print(message)
# AFTER (v0.1.0) - Uses minimal system prompt by default
# To get the old behavior, explicitly request Claude Code's preset:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
system_prompt={"type": "preset", "preset": "claude_code"} # Use the preset
),
):
print(message)
# Or use a custom system prompt:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(system_prompt="You are a helpful coding assistant"),
):
print(message)
asyncio.run(main())
```
**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.
@@ -233,21 +239,25 @@ const projectOnlyResult = query({
```python Python theme={null}
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(setting_sources=[]), # No filesystem settings loaded
):
print(message)
# Or load only specific sources:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
setting_sources=["project"] # Only project settings
),
):
print(message)
import asyncio
async def main():
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(setting_sources=[]), # No filesystem settings loaded
):
print(message)
# Or load only specific sources:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
setting_sources=["project"] # Only project settings
),
):
print(message)
asyncio.run(main())
```
Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in.
agent-sdk/overview+6-2
@@ -7,7 +7,7 @@ source: https://code.claude.com/docs/en/agent-sdk/overview.md
> Build production AI agents with Claude Code as a library
Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript. For the thinking behind agent harness design, see [A harness for every task: dynamic workflows in Claude Code](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code) on the blog.
Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript. For other languages, [run the CLI programmatically](/en/headless) with the `-p` flag and `--output-format json`. For the thinking behind agent harness design, see [A harness for every task: dynamic workflows in Claude Code](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code) on the blog.
```python Python theme={null}
import asyncio
@@ -151,6 +151,8 @@ Your agent can read files, run commands, and search codebases out of the box. Ke
| **WebFetch** | Fetch and parse web page content |
| **[AskUserQuestion](/en/agent-sdk/user-input#handle-clarifying-questions)** | Ask the user clarifying questions with multiple choice options |
For the full list, including scheduling and worktree tools, see the [tools reference](/en/tools-reference).
This example creates an agent that searches your codebase for TODO comments:
```python Python theme={null}
@@ -200,6 +202,7 @@ async def main():
async for message in query(
prompt="Refactor utils.py to improve readability",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit"],
permission_mode="acceptEdits",
hooks={
"PostToolUse": [
@@ -227,6 +230,7 @@ const logFileChange: HookCallback = async (input) => {
for await (const message of query({
prompt: "Refactor utils.py to improve readability",
options: {
allowedTools: ["Read", "Edit"],
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
@@ -335,7 +339,7 @@ Control exactly which tools your agent can use. Allow safe operations, block dan
For interactive approval prompts and the `AskUserQuestion` tool, see [Handle approvals and user input](/en/agent-sdk/user-input).
This example creates a read-only agent that can analyze but not modify code. `allowed_tools` pre-approves `Read`, `Glob`, and `Grep`.
This example creates a read-only agent that can analyze but not modify code. `allowed_tools` pre-approves `Read`, `Glob`, and `Grep` so they run without prompting. Tools not listed are still available but fall through to the permission mode; to block tools entirely, use `disallowed_tools`.
```python Python theme={null}
import asyncio
agent-sdk/sessions+52-32

セッションの永続化と、異なるホスト間でのセッション共有に関する実装の詳細が拡充されました。

@@ -92,6 +92,8 @@ async def main():
asyncio.run(main())
```
Each query prints the agent's text response followed by a status line from the result message, such as `[done: success, cost: $0.0042]`.
See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claudesdkclient) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.
### TypeScript: `continue: true`
@@ -179,6 +181,8 @@ for await (const message of query({
console.log(`Session ID: ${sessionId}`);
```
When the query completes, the script prints the agent's response followed by a line such as `Session ID: 5b3f2c1a-8d4e-4f6b-9a7c-2e1d0f9b8a6c`. In the next sections, you pass this ID to `resume`.
### Resume by ID
Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:
@@ -190,16 +194,24 @@ Pass a session ID to `resume` to return to that specific session. The agent pick
This example resumes the session from [Capture the session ID](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:
```python Python theme={null}
# Earlier session analyzed the code; now build on that analysis
async for message in query(
prompt="Now implement the refactoring you suggested",
options=ClaudeAgentOptions(
resume=session_id,
allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"],
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
session_id = "..." # The ID you captured in the previous example
async def main():
# Earlier session analyzed the code; now build on that analysis
async for message in query(
prompt="Now implement the refactoring you suggested",
options=ClaudeAgentOptions(
resume=session_id,
allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"],
),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
```
```typescript TypeScript theme={null}
@@ -236,30 +248,38 @@ Forking branches the conversation history, not the filesystem. If a forked agent
This example builds on [Capture the session ID](#capture-the-session-id): you've already analyzed an auth module in `session_id` and want to explore OAuth2 without losing the JWT-focused thread. The first block forks the session and captures the fork's ID (`forked_id`); the second block resumes the original `session_id` to continue down the JWT path. You now have two session IDs pointing at two separate histories:
```python Python theme={null}
# Fork: branch from session_id into a new session
forked_id = None
async for message in query(
prompt="Instead of JWT, outline how OAuth2 would work for the auth module",
options=ClaudeAgentOptions(
resume=session_id,
fork_session=True,
max_turns=5,
),
):
if isinstance(message, ResultMessage):
forked_id = message.session_id # The fork's ID, distinct from session_id
if message.subtype == "success":
print(message.result)
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
session_id = "..." # The ID you captured in the previous example
async def main():
# Fork: branch from session_id into a new session
forked_id = None
async for message in query(
prompt="Instead of JWT, outline how OAuth2 would work for the auth module",
options=ClaudeAgentOptions(
resume=session_id,
fork_session=True,
max_turns=5,
),
):
if isinstance(message, ResultMessage):
forked_id = message.session_id # The fork's ID, distinct from session_id
if message.subtype == "success":
print(message.result)
print(f"Forked session: {forked_id}")
print(f"Forked session: {forked_id}")
# Original session is untouched; resuming it continues the JWT thread
async for message in query(
prompt="Continue with the JWT approach",
options=ClaudeAgentOptions(resume=session_id),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
# Original session is untouched; resuming it continues the JWT thread
async for message in query(
prompt="Continue with the JWT approach",
options=ClaudeAgentOptions(resume=session_id),
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
```
```typescript TypeScript theme={null}
agent-sdk/streaming-vs-single-mode+10-4

ストリーミングモードとシングルモードの使い分けおよび、それぞれのイベント処理の違いが明確化されました。

@@ -74,6 +74,8 @@ Maintain conversation context across multiple turns naturally
### Implementation Example
These examples read an image named `diagram.png` from the working directory. Create one there first, or change the filename to point at your own image.
```typescript TypeScript theme={null}
import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
import { readFile } from "fs/promises";
@@ -193,6 +195,8 @@ async def streaming_analysis():
asyncio.run(streaming_analysis())
```
When you run the example, the TypeScript version prints each response as it completes. The Python version's `receive_response()` loop ends at the first result message, so it prints the security analysis; to read both responses, use one `query()` and `receive_response()` pair per message as shown in the [Python reference's example of continuing a conversation](/en/agent-sdk/python#example-continuing-a-conversation).
In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.
In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
@@ -229,7 +233,7 @@ import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Explain the authentication flow",
options: {
maxTurns: 1,
maxTurns: 5,
allowedTools: ["Read", "Grep"]
}
})) {
@@ -243,7 +247,7 @@ for await (const message of query({
prompt: "Now explain the authorization process",
options: {
continue: true,
maxTurns: 1
maxTurns: 5
}
})) {
if (message.type === "result" && message.subtype === "success") {
@@ -260,7 +264,7 @@ async def single_message_example():
# Simple one-shot query using query() function
async for message in query(
prompt="Explain the authentication flow",
options=ClaudeAgentOptions(max_turns=1, allowed_tools=["Read", "Grep"]),
options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),
):
if isinstance(message, ResultMessage):
print(message.result)
@@ -268,10 +272,12 @@ async def single_message_example():
# Continue conversation with session management
async for message in query(
prompt="Now explain the authorization process",
options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),
):
if isinstance(message, ResultMessage):
print(message.result)
asyncio.run(single_message_example())
```
When you run the example, each query prints its final result text: first the authentication explanation, then the authorization explanation.
channels+4-4
@@ -33,7 +33,7 @@ In Claude Code, run:
/plugin install telegram@claude-plugins-official
```
If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
After installing, run `/reload-plugins` to activate the plugin's configure command.
@@ -90,7 +90,7 @@ In Claude Code, run:
/plugin install discord@claude-plugins-official
```
If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
After installing, run `/reload-plugins` to activate the plugin's configure command.
@@ -138,7 +138,7 @@ In Claude Code, run:
/plugin install imessage@claude-plugins-official
```
If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
Exit Claude Code and restart with the channel flag:
@@ -178,7 +178,7 @@ Start a Claude Code session and run the install command:
/plugin install fakechat@claude-plugins-official
```
If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
Exit Claude Code, then restart with `--channels` and pass the fakechat plugin you installed:
claude-code-on-the-web+17-3

Web環境でClaude Codeを動作させる際の設定や制限事項について、最新のインターフェースに基づいた説明が追加されました。

@@ -253,7 +253,7 @@ To install dependencies only in cloud sessions, add a SessionStart hook to your
}
```
Create the script at `scripts/install_pkgs.sh` and make it executable with `chmod +x`. The `CLAUDE_CODE_REMOTE` environment variable is set to `true` in cloud sessions, so you can use it to skip local execution:
Create the script at `scripts/install_pkgs.sh`. The `CLAUDE_CODE_REMOTE` environment variable is set to `true` in cloud sessions, so you can use it to skip local execution:
```bash
#!/bin/bash
@@ -267,6 +267,12 @@ pip install -r requirements.txt
exit 0
```
Then make the script executable:
```bash
chmod +x scripts/install_pkgs.sh
```
SessionStart hooks have some limitations in cloud sessions:
- **No cloud-only scoping**: hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.
@@ -558,7 +564,7 @@ When using **Trusted** network access, the following domains are allowed by defa
## Move tasks between web and terminal
These workflows require the [Claude Code CLI](/en/quickstart) signed in to the same claude.ai account. You can start new cloud sessions from your terminal, or pull cloud sessions into your terminal to continue locally. Cloud sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app.
These workflows require the [Claude Code CLI](/en/quickstart) signed in to the same claude.ai account. You can start new cloud sessions from your terminal, or pull cloud sessions into your terminal to continue locally. Cloud sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app. The `--cloud` and `--teleport` flags don't appear in `claude --help` output, but the CLI accepts them as shown below.
From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with `--teleport`, but you can't push an existing terminal session to the web. The `--cloud` flag creates a new cloud session for your current repository. The [Desktop app](/en/desktop#continue-in-another-surface) provides a Continue in menu that can send a local session to the web.
@@ -649,7 +655,7 @@ Teleport checks these requirements before resuming a session. If any requirement
#### `--teleport` is unavailable
Teleport requires claude.ai subscription authentication. If you're authenticated via API key, Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry, run `/login` to sign in with your claude.ai account instead. If you're already signed in via claude.ai and `--teleport` is still unavailable, your organization may have disabled cloud sessions.
Teleport requires claude.ai subscription authentication. If you're authenticated via API key, run `/login` to sign in with your claude.ai account instead. On Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry, `--teleport` stops with `Cloud sessions aren't available with <provider>` because cloud sessions run on Anthropic's infrastructure and aren't available through those providers. If you're already signed in via claude.ai and `--teleport` is still unavailable, your organization may have disabled cloud sessions.
## Work with sessions
@@ -763,6 +769,14 @@ If a new session fails to start with `Session creation failed` or stalls at prov
- Retry after a minute, as capacity is provisioned on demand
- Confirm your repository is reachable. The connecting GitHub account must have access to the repository on GitHub, either through the Claude GitHub App authorization or a `gh` token synced via `/web-setup`. Installing the App on the repository isn't required. See [GitHub authentication options](#github-authentication-options).
### Unable to get organization UUID
`claude --cloud` and `claude --teleport` require sign-in with a claude.ai account. If you authenticate with an API key, or your stored account details are stale, these commands fail with `Unable to get organization UUID` or a message that API key authentication is not sufficient.
Run `/login` to sign in with your claude.ai account, then retry the command.
On Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry, the commands stop earlier with `Cloud sessions aren't available with <provider>`. Cloud sessions run on Anthropic's infrastructure and aren't available through those providers.
### Remote Control session expired or access denied
`--teleport` connects through the same Remote Control session infrastructure that cloud sessions use, so authentication and session-expiry errors surface with Remote Control wording. You may see `Remote Control session expired` or `Access denied`. The connection token is short-lived and scoped to your account.
context-window+1-1
@@ -50,7 +50,7 @@ If you need a larger window rather than a smaller conversation, Fable 5, Sonnet
## Check your own session
The visualization uses representative numbers. To see your actual context usage at any point, run `/context` for a live breakdown by category with optimization suggestions. Run `/memory` to check which CLAUDE.md and auto memory files loaded at startup.
The visualization uses representative numbers. To see your actual context usage at any point, run `/context` for a live breakdown by category with optimization suggestions, including which CLAUDE.md and auto memory files loaded. Run `/memory` to open and edit those files.
## Related resources
debug-your-config+5-5
@@ -13,13 +13,13 @@ For installation, authentication, and connectivity problems, see [Troubleshoot i
## See what loaded into context
The `/context` command shows everything occupying the context window for the current session, broken down by category: system prompt, memory files, skills, custom subagents with the source each loaded from, MCP tools, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all.
The `/context` command shows everything occupying the context window for the current session, broken down by category: system prompt, system tools, MCP tools, custom subagents with the source each loaded from, memory files, skills, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all.
For detail on a specific category, follow up with the dedicated command:
| Command | Shows |
| :- | :- |
| `/memory` | Which `CLAUDE.md` and rules files loaded, plus auto-memory entries |
| `/memory` | Memory file locations across user and project scopes with the option to open each in your editor, plus access to the auto memory folder and the auto memory toggle |
| `/skills` | Available skills from project, user, and plugin sources |
| `/hooks` | Active hook configurations |
| `/mcp` | Connected MCP servers and their status |
@@ -28,9 +28,9 @@ For detail on a specific category, follow up with the dedicated command:
| `/debug [issue]` | Enables debug logging for the session and prompts Claude to diagnose using the log output and settings paths |
| `/status` | Active settings sources, including whether managed settings are in effect |
If a memory file is missing from `/memory`, check its location against [how CLAUDE.md files load](/en/memory#how-claude-md-files-load). Subdirectory `CLAUDE.md` files load on demand when Claude reads a file in that directory with the Read tool, not at session start.
If a memory file is missing from the `/context` breakdown, check its location against [how CLAUDE.md files load](/en/memory#how-claude-md-files-load). Subdirectory `CLAUDE.md` files load on demand when Claude reads a file in that directory with the Read tool, not at session start.
If `/memory` confirms the file loaded but Claude still isn't following a particular instruction, the issue is likely how the instruction is written rather than whether it loaded. CLAUDE.md works well for the kinds of guidance you'd give a new teammate, such as project conventions, build commands, and where files belong.
If `/context` confirms the file loaded but Claude still isn't following a particular instruction, the issue is likely how the instruction is written rather than whether it loaded. CLAUDE.md works well for the kinds of guidance you'd give a new teammate, such as project conventions, build commands, and where files belong.
Adherence drops when an instruction is vague enough to interpret multiple ways, when two files give conflicting direction, or when the file has grown long enough that individual rules get less attention. [Write effective instructions](/en/memory#write-effective-instructions) covers the specificity, size, and structure patterns that keep adherence high.
@@ -80,7 +80,7 @@ If the problem persists in safe mode, or your settings themselves are suspect, c
cd /tmp && CLAUDE_CONFIG_DIR=/tmp/claude-clean claude
```
The clean session has no user or project settings, hooks, MCP servers, plugins, or memory.
The clean session has no user or project settings, hooks, MCP servers, plugins, or memory. On the first launch, expect the first-run setup screens, starting with theme selection. If you see them, the clean configuration directory is in effect. Later launches with the same directory skip these screens because Claude Code saves onboarding state there.
- Managed settings still apply if your organization deploys them, since they live at a system path outside `~/.claude`
- On Linux and Windows, you'll be prompted to log in again because credentials are stored under the configuration directory
discover-plugins+1-1
@@ -31,7 +31,7 @@ To install a plugin from the official marketplace, use `/plugin install <name>@c
/plugin install github@claude-plugins-official
```
If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
The official marketplace is curated by Anthropic, and inclusion is at Anthropic's discretion. The in-app submission forms add plugins to the [community marketplace](#community-marketplace), not the official one. To distribute plugins independently, [create your own marketplace](/en/plugin-marketplaces) and share it with users.
github-enterprise-server+6-2
@@ -72,7 +72,7 @@ Your GHES instance must be reachable from Anthropic infrastructure so Claude can
Once an Owner has connected the GHES instance, no developer-side configuration is needed. Claude Code detects your GHES hostname automatically from the git remote in your working directory.
Clone a repository from your GHES instance as you normally would:
Clone a repository from your GHES instance as you normally would, replacing `github.example.com` and the repository path with your GHES hostname and repository:
```bash
git clone git@github.example.com:platform/api-service.git
@@ -107,7 +107,7 @@ GitHub Enterprise connections on claude.ai are per user when a marketplace is ad
### Add a GHES marketplace
The `owner/repo` shorthand always resolves to github.com. For GHES-hosted marketplaces, use the full git URL. HTTPS URLs are recommended:
The `owner/repo` shorthand always resolves to github.com. For GHES-hosted marketplaces, use the full git URL, replacing `github.example.com` and the repository path with your own. HTTPS URLs are recommended:
```bash
/plugin marketplace add https://github.example.com/platform/claude-plugins.git
@@ -193,6 +193,10 @@ On other claude.ai surfaces, a "Repository not found. If it's private, GitHub ac
If reviews or web sessions time out, your GHES instance may not be reachable from Anthropic infrastructure. Confirm your firewall allows inbound connections from the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).
### Session start fails with `Unable to get organization UUID`
Web sessions require a Team or Enterprise organization. Sign in with `/login` using your organization account. If you authenticate with an API key instead, web sessions fail earlier with a message asking you to run `/login`.
## Related resources
These pages cover the features referenced throughout this guide in more depth:
hooks+6-0

新しいフックポイントの追加と、特定のライフサイクルイベントで実行される処理の定義が更新されました。

@@ -100,6 +100,8 @@ else
fi
```
This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them.
Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:
The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:
@@ -927,6 +929,8 @@ git -C ~/.claude/skills/team-skills pull --quiet 2>/dev/null || \
echo '{"hookSpecificOutput": {"hookEventName": "SessionStart", "reloadSkills": true}}'
```
The repository URL is a placeholder; replace it with your own skills repository. With the placeholder, the clone fails and prints a `fatal:` message to stderr. Stderr from a SessionStart hook that exits 0 is informational only, so the `reloadSkills` request still applies.
#### Persist environment variables
SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent Bash commands.
@@ -981,6 +985,8 @@ The matcher value corresponds to the CLI flag that triggered the hook:
`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don't currently fire Setup hooks.
On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries.
Because Setup doesn't fire on every launch, a plugin that needs a dependency installed can't rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](/en/plugins-reference#persistent-data-directory) for where to store installed dependencies.
#### Setup input
interactive-mode+1-1
@@ -25,7 +25,7 @@ See [Terminal configuration](/en/terminal-config) for details.
| :- | :- | :- |
| `Ctrl+C` | Interrupt, or clear input | Interrupts a running operation. If nothing is running, the first press clears the prompt input and a second press exits Claude Code |
| `Ctrl+X Ctrl+K` | Stop all running [background subagents](/en/sub-agents#run-subagents-in-foreground-or-background) in this session. Press twice within 3 seconds to confirm | Subagent control |
| `Ctrl+D` | Exit Claude Code session | EOF signal |
| `Ctrl+D` | Exit Claude Code session | The first press shows a confirmation hint and a second press within 800ms exits. When the prompt has text, `Ctrl+D` deletes the character after the cursor instead |
| `Ctrl+G` or `Ctrl+X Ctrl+E` | Open in default text editor | Edit your prompt or custom response in your default text editor. `Ctrl+X Ctrl+E` is the readline-native binding. Turn on **Show last response in external editor** in `/config` to prepend Claude's previous reply as `#`-commented context above your prompt; Claude Code strips the comment block when you save |
| `Ctrl+L` | Redraw screen | Forces a full terminal redraw. Input and conversation history are kept. Use this to recover if the display becomes garbled or partially blank |
| `Ctrl+O` | Toggle transcript viewer | Shows detailed tool usage and execution, with a timestamp and the model used on each assistant message. Also expands MCP calls, which collapse to a single line like "Called slack 3 times" by default |
keybindings+1-1
@@ -78,7 +78,7 @@ Actions available in the `Global` context:
| Action | Default | Description |
| :- | :- | :- |
| `app:interrupt` | Ctrl+C | Cancel current operation |
| `app:exit` | Ctrl+D | Exit Claude Code |
| `app:exit` | Ctrl+D | Exit Claude Code. Press twice within 800ms to confirm |
| `app:redraw` | (unbound) | Force terminal redraw |
| `app:toggleTodos` | Ctrl+T | Toggle visibility of Claude's to-do checklist. This is not the [`/tasks`](/en/commands) background-task view |
| `app:toggleTranscript` | Ctrl+O | Toggle verbose transcript |
large-codebases+2-0
@@ -199,6 +199,8 @@ The official marketplace has plugins for TypeScript, Python, Go, Rust, and other
/plugin install typescript-lsp@claude-plugins-official
```
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
To enable a plugin for everyone in the repository rather than installing it yourself, add it to the [`enabledPlugins` project setting](/en/settings#plugin-settings).
Code intelligence plugins require the language's language server binary on each developer's machine. See [which binary each language requires](/en/discover-plugins#code-intelligence). Installing from the official marketplace requires network access to GitHub, where the marketplace is hosted. On a restricted network, [add the marketplace from an internal Git host or local path](/en/discover-plugins#add-from-other-git-hosts) instead.
llm-gateway-connect+2-2
@@ -20,7 +20,7 @@ Administrators can distribute the gateway address and credential through [manage
Run `claude`. If it opens to the login screen instead of a session, no gateway credential was distributed; [configure it yourself](#configure-claude-code-yourself) below.
If Claude Code started a session without showing the login screen, run `/status`, open the **Status** tab, and check two lines:
If Claude Code started a session without showing the login screen, run `/status`, which opens on the **Status** tab, and check two lines:
- `Anthropic base URL`: this line only appears when a gateway address is set. If it isn't there, Claude Code isn't pointed at the gateway; [configure it yourself](#configure-claude-code-yourself) below.
- `Auth token` or `API key`: a line naming `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`, or an `apiKeyHelper` confirms a gateway credential is active. A `Login method` line naming a claude.ai account instead means the credential wasn't distributed; [set it yourself](#set-the-credential-variable).
@@ -426,7 +426,7 @@ These are the most common errors when running Claude Code through a gateway, wit
| A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead. | A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior | Unset the variable to use the saved login, or run `/logout` to use the gateway credential |
| `401` errors naming an invalid or unrecognized token | The credential isn't one the gateway issued, or it's in a header the gateway doesn't read | Confirm the variable matches your credential kind in the [credential table](#set-the-credential-variable), and regenerate the key at the gateway if it was revoked |
| `Your apiKeyHelper script is failing` | The command in the [`apiKeyHelper`](/en/settings#available-settings) setting exited with an error, timed out, or printed nothing, so requests carry a placeholder key | Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](/en/errors#your-apikeyhelper-script-is-failing) |
| `Unable to connect to API (ConnectionRefused)`, or `(ECONNREFUSED)` from npm installs, often after a silent pause while Claude Code [retries with backoff](/en/errors#automatic-retries) | Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway | Run the [curl test above](#verify-the-connection), which fails immediately with the same cause, and confirm the URL and network path with your gateway team |
| `Unable to connect to API (ConnectionRefused)` when nothing answers at the address, `Unable to connect to API (FailedToOpenSocket)` when the hostname doesn't resolve, or `(ECONNREFUSED)` from npm installs, often after a silent pause while Claude Code [retries with backoff](/en/errors#automatic-retries) | Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway | Run the [curl test above](#verify-the-connection), which fails immediately with the same cause, and confirm the URL and network path with your gateway team |
| `API returned an empty or malformed response (HTTP 200)` | The gateway or an intermediate proxy returned a non-API response, often an HTML error or login page | Test with the [curl request above](#verify-the-connection); fix the gateway route that returns non-JSON |
| `400` errors naming `context_management`, `Extra inputs are not permitted`, or other unrecognized fields | The gateway forwards requests to an upstream that rejects fields Claude Code sends to Anthropic-format endpoints | Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, which suppresses most pre-release fields; see [feature pass-through](/en/llm-gateway-protocol#feature-pass-through). Some betas aren't gated by this flag; for those, set the matching `CLAUDE_CODE_USE_*` provider variable so Claude Code sends only what that provider accepts |
| `400` errors naming `thinking` or `adaptive`, such as `Input tag 'adaptive' found` | The upstream model build doesn't accept adaptive reasoning, which Claude Code requests for Claude 4.6 and later models | Upgrade the gateway's upstream. On Opus 4.6 and Sonnet 4.6, `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` works instead. The [model configuration](/en/model-config) capability variables apply only to the provider configurations, such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, not behind an `ANTHROPIC_BASE_URL` gateway |
mcp-quickstart+12-6

MCPサーバーを迅速にセットアップするための手順が、最新のSDK仕様に合わせて調整されました。

@@ -41,7 +41,7 @@ The parts of the command:
- `claude-code-docs`: a name you make up. Calling the same server `docs` would work identically. Claude Code uses whatever name you pick to label the server's tools in Claude's output and to refer to the server in commands like `claude mcp remove`.
- `https://code.claude.com/docs/mcp`: the URL where the server is hosted.
The command prints a confirmation like `Added HTTP MCP server claude-code-docs with URL: https://code.claude.com/docs/mcp to local config`. The `local config` part means the server is registered to you, in this project: if you start Claude Code in a different project, this server isn't active there. To register a server once for all your projects, add it at user scope, covered in [Change server scope](#change-server-scope).
The command prints a confirmation like `Added HTTP MCP server claude-code-docs with URL: https://code.claude.com/docs/mcp to local config`, followed by a `File modified:` line showing the configuration file it wrote. The `local config` part means the server is registered to you, in this project: if you start Claude Code in a different project, this server isn't active there. To register a server once for all your projects, add it at user scope, covered in [Change server scope](#change-server-scope).
Confirm the server appears in your server list and check its status:
@@ -53,12 +53,14 @@ The server appears with a status indicator:
| Status | Meaning |
| :- | :- |
| `✓ Connected` | Ready to use. This is what you should see for `claude-code-docs` |
| `✔ Connected` | Ready to use. This is what you should see for `claude-code-docs` |
| `! Connected · tools fetch failed` | The server connected but couldn't list its tools. Run `claude mcp get <name>` for the error detail |
| `! Needs authentication` | The server is reachable but needs a browser sign-in, or a token passed with `--header`. See [Connect a server that requires sign-in](#connect-a-server-that-requires-sign-in) |
| `✗ Failed to connect` | Server didn't respond. See [Troubleshooting](#troubleshooting) |
| `✗ Connection error` | The connection attempt threw an error. See [Troubleshooting](#troubleshooting) |
| `⏸ Pending approval` | A project-scoped server you haven't approved yet. See [Edit .mcp.json directly](#edit-mcp-json-directly) |
| `✘ Failed to connect` | Server didn't respond. See [Troubleshooting](#troubleshooting) |
| `✘ Connection error` | The connection attempt threw an error. See [Troubleshooting](#troubleshooting) |
| ``⏸ Pending approval (run `claude` to approve)`` | A project-scoped server you haven't approved yet. See [Edit .mcp.json directly](#edit-mcp-json-directly) |
Some legacy Windows consoles, such as the default console on Windows 10, don't support these Unicode glyphs and show `√` and `×` in place of `✔` and `✘`.
Start a session and ask Claude to use the new server by name:
@@ -80,6 +82,8 @@ This step is optional. When you're done experimenting, you can remove the server
claude mcp remove claude-code-docs
```
The command confirms with `Removed MCP server "claude-code-docs" from local config` and a `File modified:` line showing the file it updated.
Each connected server takes some space in [Claude's context window](/en/how-claude-code-works#the-context-window) because its tool names and server instructions load into every session. Removing servers you no longer use keeps that space free.
## Where servers are saved
@@ -156,6 +160,8 @@ This command differs from the hosted example in three ways:
- Everything after the `--` separator is the command Claude Code runs to start the server.
- `-y` tells `npx` to install the package without prompting.
The command prints a confirmation like `Added stdio MCP server playwright with command: npx -y @playwright/mcp@latest to local config`, followed by a `File modified:` line showing the configuration file it wrote.
Playwright drives whichever Chrome is already installed on your machine. To use a different browser, append `--browser` with the browser name, for example `--browser firefox`, after `@playwright/mcp@latest`.
The `Added` confirmation means the entry was saved, not that the command runs. Check the connection:
@@ -164,7 +170,7 @@ The `Added` confirmation means the entry was saved, not that the command runs. C
claude mcp list
```
The first check can show `✗ Failed to connect` while `npx` downloads the package, so wait a moment and run it again.
The first check can show `✘ Failed to connect` while `npx` downloads the package, so wait a moment and run it again. Once the download finishes, the status changes to `✔ Connected`. If it still shows `✘ Failed to connect` after a couple of retries, see [Troubleshooting](#troubleshooting).
Give Claude a task that needs the browser:
mcp+2-2
@@ -40,7 +40,7 @@ In a Claude Code session, run:
/plugin install mcp-server-dev@claude-plugins-official
```
If Claude Code reports that the marketplace is not found, run `/plugin marketplace add anthropics/claude-plugins-official` first, then retry the install. Once installed, run `/reload-plugins` to activate it in the current session.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install. Once installed, run `/reload-plugins` to activate it in the current session.
```
/mcp-server-dev:build-mcp-server
@@ -151,7 +151,7 @@ claude mcp remove github
/mcp
```
Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` as `⏸ Pending approval`. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows pending servers as `⏸ Pending approval` and rejected servers as `✗ Rejected`.
Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` and `claude mcp get <name>` as ``⏸ Pending approval (run `claude` to approve)``. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows rejected servers as `✘ Rejected (see disabledMcpjsonServers in settings)`.
As of v2.1.196, `claude mcp list` and `claude mcp get` read `.mcp.json` approvals only from settings files that aren't checked into the repository until you trust the workspace by running `claude` in it and accepting the workspace trust dialog. A cloned repository can't approve its own servers: [`enableAllProjectMcpServers` or `enabledMcpjsonServers`](/en/settings#available-settings) committed to the project's `.claude/settings.json` is ignored in an untrusted folder, and the server stays at `⏸ Pending approval` instead of being connected and health-checked.
memory+2-2
@@ -380,7 +380,7 @@ Auto memory files are plain markdown you can edit or delete at any time. Run [`/
## View and edit with `/memory`
The `/memory` command lists all CLAUDE.md, CLAUDE.local.md, and rules files loaded in your current session, lets you toggle auto memory on or off, and provides a link to open the auto memory folder. Select any file to open it in your editor.
The `/memory` command lists your CLAUDE.md, CLAUDE.local.md, and other memory file locations across user and project scopes, lets you toggle auto memory on or off, and provides an option to open the auto memory folder. Select any file to open it in your editor. To check which files actually loaded into the current session, run `/context`.
When you ask Claude to remember something, like "always use pnpm, not npm" or "remember that the API tests require a local Redis instance," Claude saves it to auto memory. To add instructions to CLAUDE.md instead, ask Claude directly, like "add this to CLAUDE.md," or edit the file yourself via `/memory`.
@@ -394,7 +394,7 @@ CLAUDE.md content is delivered as a user message after the system prompt, not as
To debug:
- Run `/memory` to verify your CLAUDE.md and CLAUDE.local.md files are being loaded. If a file isn't listed, Claude can't see it.
- Run `/context` to verify your CLAUDE.md and CLAUDE.local.md files loaded. If a file is missing from the breakdown, Claude can't see it. Use `/memory` to open and edit the files.
- Check that the relevant CLAUDE.md is in a location that gets loaded for your session (see [Choose where to put CLAUDE.md files](#choose-where-to-put-claude-md-files)).
- Make instructions more specific. "Use 2-space indentation" works better than "format code nicely."
- Look for conflicting instructions across CLAUDE.md files. If two files give different guidance for the same behavior, Claude may pick one arbitrarily.
model-config+3-1
@@ -444,7 +444,7 @@ You can turn on ultracode through any of the following:
Passing `ultracode` to the `--effort` flag or the Agent SDK `effortLevel` value requires Claude Code v2.1.203 or later. Before v2.1.203, `--effort ultracode` printed `Unknown --effort value 'ultracode'` and the session started at the default effort.
The persisted `effortLevel` setting and the `CLAUDE_CODE_EFFORT_LEVEL` environment variable don't accept `ultracode`.
The persisted `effortLevel` setting and the `CLAUDE_CODE_EFFORT_LEVEL` environment variable don't accept `ultracode`. When `CLAUDE_CODE_EFFORT_LEVEL` is set to a level other than `xhigh`, requests run at that level and ultracode's workflow orchestration stays inactive. Selecting ultracode then shows a warning that the environment variable overrides effort for the session.
When ultracode isn't available, for example when [workflows are turned off](/en/workflows#turn-workflows-off), `--effort ultracode` sets `xhigh` effort only.
@@ -480,6 +480,8 @@ You can change effort through any of the following:
The environment variable takes precedence over all other methods, then your configured level, then the model default. Frontmatter effort applies when that skill or subagent is active, overriding the session level but not the environment variable.
The `effortLevel` key in [managed settings](/en/settings#settings-precedence) is a starting default, not enforcement: users can change it for a session with `/effort` or `--effort`, and the managed value re-asserts as the default in new sessions.
The effort slider appears in `/model` when a supported model is selected. The current effort level is also displayed next to the logo and spinner, for example "with low effort", so you can confirm which setting is active without opening `/model`.
#### Adaptive reasoning and fixed thinking budgets
quickstart+6-6
@@ -26,19 +26,19 @@ To install Claude Code, use one of the following methods:
**macOS, Linux, WSL:**
```bash theme={null}
```bash theme={null} theme={null} theme={null}
curl -fsSL https://claude.ai/install.sh | bash
```
**Windows PowerShell:**
```powershell theme={null}
```powershell theme={null} theme={null} theme={null}
irm https://claude.ai/install.ps1 | iex
```
**Windows CMD:**
```batch theme={null}
```batch theme={null} theme={null} theme={null}
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
```
@@ -50,7 +50,7 @@ If the install command fails with `syntax error near unexpected token '<'`, a `4
Native installations automatically update in the background to keep you on the latest version.
```bash theme={null}
```bash theme={null} theme={null} theme={null}
brew install --cask claude-code
```
@@ -58,7 +58,7 @@ Homebrew offers two casks. `claude-code` tracks the stable release channel, whic
Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes.
```powershell theme={null}
```powershell theme={null} theme={null} theme={null}
winget install Anthropic.ClaudeCode
```
@@ -256,7 +256,7 @@ Here are the most important commands for daily use. Shell commands run from your
| - | - | - |
| `/clear` | Clear conversation history | `/clear` |
| `/help` | Show available commands | `/help` |
| `/exit` or Ctrl+D | Exit Claude Code | `/exit` |
| `/exit` or Ctrl+D twice | Exit Claude Code | `/exit` |
See the [CLI reference](/en/cli-reference) for the complete list of shell commands and the [commands reference](/en/commands) for the complete list of session commands.
remote-control+1-1
@@ -27,7 +27,7 @@ This page covers setup, how to start and connect to sessions, and how Remote Con
Before using Remote Control, confirm that your environment meets these conditions:
- **Subscription**: available on Pro, Max, Team, and Enterprise plans. API keys are not supported. On Team and Enterprise, an Owner must first enable the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).
- **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven't already.
- **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven't already. Without an eligible login, `claude remote-control` exits with an error, while `claude --remote-control` still starts an interactive session and shows a Remote Control failure notification shortly after launch.
- **API endpoint**: not available on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. As of v2.1.196, Remote Control is also disabled when [`ANTHROPIC_BASE_URL`](/en/env-vars) points at a host other than `api.anthropic.com`, such as an [LLM gateway](/en/llm-gateway) or proxy. Unset the variable to use Remote Control.
- **Workspace trust**: run `claude` in your project directory at least once to accept the workspace trust dialog.
sandbox-environments+1-1
@@ -76,7 +76,7 @@ To put built-in tools, MCP servers, and hooks all behind one OS boundary, run th
The [`@anthropic-ai/sandbox-runtime`](https://github.com/anthropic-experimental/sandbox-runtime) package wraps an entire process in the same Seatbelt or bubblewrap isolation that the built-in Bash sandbox uses. Running Claude Code through it constrains every tool, hook, and MCP server in the session, not only Bash. The runtime is a beta research preview, and its configuration format may change as the package evolves.
The runtime denies all write and network access by default, so configure it before launching Claude Code through it. In `~/.srt-settings.json`, or a file you pass with `--settings`, allow write access to at least your project directory and Claude Code's configuration paths `~/.claude` and `~/.claude.json`. Allow the network domains your session needs, including `api.anthropic.com` or your configured provider's endpoint. See the package [README](https://github.com/anthropic-experimental/sandbox-runtime) for the full configuration schema.
The runtime denies all write and network access by default, so configure it before launching Claude Code through it. In `~/.srt-settings.json`, or a file you pass with `--settings`, allow write access to at least your project directory, Claude Code's configuration paths `~/.claude` and `~/.claude.json`, and `/tmp`, where Claude Code writes runtime files. Allow the network domains your session needs, including `api.anthropic.com` or your configured provider's endpoint. See the package [README](https://github.com/anthropic-experimental/sandbox-runtime) for the full configuration schema.
Once the settings file is in place, launch Claude Code with `npx` and pass `claude` as the command to wrap:
security-guidance+1-1
@@ -29,7 +29,7 @@ In a Claude Code session, install from the [official Anthropic marketplace](/en/
/plugin install security-guidance@claude-plugins-official
```
The install prompts for a scope. Choose user scope to write the plugin to your user settings, so it loads in every new local session you start on this machine. If Claude Code reports that the marketplace is not found, run `/plugin marketplace add anthropics/claude-plugins-official` first, then retry the install.
The install prompts for a scope. Choose user scope to write the plugin to your user settings, so it loads in every new local session you start on this machine. If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
Then activate it in the current session with `/reload-plugins`, which applies pending plugin changes without a restart:
skills+1-1
@@ -592,7 +592,7 @@ The [`skill-creator` plugin](https://github.com/anthropics/claude-plugins-offici
/plugin install skill-creator@claude-plugins-official
```
If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.
After installing, run `/reload-plugins` to make the plugin's skills available in the current session. Then ask Claude to evaluate an existing skill, for example `evaluate my summarize-changes skill with skill-creator`. The plugin walks you through writing test cases and runs the loop:
terminal-config+10-5

ターミナル環境における表示設定や、特定のシェル環境での最適化に関するオプションが更新されました。

@@ -30,7 +30,7 @@ In most terminals you can also press Shift+Enter, but support varies by terminal
| VS Code, Cursor, Devin Desktop, Alacritty, Zed | Run `/terminal-setup` once |
| gnome-terminal, JetBrains IDEs such as PyCharm and Android Studio | Not available; use Ctrl+J or `\` then Enter |
For VS Code, Cursor, Devin Desktop, Alacritty, and Zed, `/terminal-setup` writes Shift+Enter and other keybindings into the terminal's configuration file. Existing bindings are left in place; if you see a message such as `VSCode terminal Shift+Enter key binding already configured`, no change was made. Run `/terminal-setup` directly in the host terminal rather than inside tmux or screen, since it needs to write to the host terminal's configuration.
For VS Code, Cursor, Devin Desktop, Alacritty, and Zed, `/terminal-setup` writes Shift+Enter and other keybindings into the terminal's configuration file. On the first run you see a confirmation such as `Installed VSCode terminal Shift+Enter key binding`. Existing bindings are left in place; if you see a message such as `VSCode terminal Shift+Enter key binding already configured`, no change was made. Run `/terminal-setup` directly in the host terminal rather than inside tmux or screen, since it needs to write to the host terminal's configuration.
In VS Code, Cursor, and Devin Desktop, `/terminal-setup` also updates two editor settings: it sets `terminal.integrated.gpuAcceleration` to `"off"` to prevent garbled text in the integrated terminal, and it sets `terminal.integrated.mouseWheelScrollSensitivity` for smoother scrolling in [fullscreen mode](/en/fullscreen). To undo the GPU acceleration change, set it back to `"auto"` and reload the editor window.
@@ -60,7 +60,13 @@ For Ghostty, Kitty, and other terminals, look for an Option-as-Alt or Option-as-
When Claude finishes a task or pauses for a permission prompt, it fires a notification event. Surfacing this as a terminal bell or desktop notification lets you switch to other work while a long task runs.
By default Claude Code sends a desktop notification only in Ghostty, Kitty, and iTerm2. In other terminals, set [`preferredNotifChannel`](/en/settings#available-settings) to `"terminal_bell"` to ring the terminal bell instead, or configure a [Notification hook](#play-a-sound-with-a-notification-hook) for a custom sound or command.
By default Claude Code sends a desktop notification only in Ghostty, Kitty, and iTerm2. In other terminals, set [`preferredNotifChannel`](/en/settings#available-settings) to `"terminal_bell"` to ring the terminal bell instead, or configure a [Notification hook](#play-a-sound-with-a-notification-hook) for a custom sound or command. The following settings entry turns on the terminal bell:
```json ~/.claude/settings.json theme={null}
{
"preferredNotifChannel": "terminal_bell"
}
```
The desktop notification reaches your local machine over SSH, so a remote session can still alert you. Ghostty and Kitty forward it to your OS notification center without further setup. iTerm2 requires you to enable forwarding:
@@ -136,7 +142,7 @@ The following example defines a theme that keeps the dark preset but recolors th
}
```
Claude Code watches `~/.claude/themes/` and reloads when a file changes, so edits made in your editor apply to a running session without a restart.
Claude Code watches `~/.claude/themes/` and reloads when a file is added or changed, so edits made in your editor apply to a running session without a restart. If the `~/.claude/themes/` folder itself didn't exist when Claude Code started, restart once after creating your first theme file. After that, changes apply without a restart.
The reference below covers the tokens you can set in `overrides`. The interactive editor in `/theme` shows the same tokens with a live preview, plus a few single-purpose accents such as onboarding screen colors that are omitted here.
@@ -216,7 +222,6 @@ Apply only in [fullscreen rendering mode](/en/fullscreen), where messages have a
| :- | :- |
| `userMessageBackground` | Background behind your messages in the transcript |
| `userMessageBackgroundHover` | Background behind a message while hovered or expanded |
| `messageActionsBackground` | Background behind the selected message when the action bar is open |
| `bashMessageBackgroundColor` | Background behind `!` shell command entries in the transcript |
| `memoryBackgroundColor` | Background behind `#` memory entries in the transcript |
| `selectionBg` | Background of text selected with the mouse |
@@ -273,7 +278,7 @@ $env:CLAUDE_CODE_NO_FLICKER = "1"; claude
## Paste large content
When you paste more than 10,000 characters into the prompt, Claude Code collapses the input to a `[Pasted text]` placeholder so the input box stays usable. The full content is still sent to Claude when you submit.
When you paste more than 800 characters or more than two lines into the prompt, Claude Code collapses the input to a placeholder such as `[Pasted text #1 +120 lines]` so the input box stays usable. The full content is still sent to Claude when you submit.
The VS Code integrated terminal can drop characters from very large pastes before they reach Claude Code, so prefer file-based workflows there. For very large inputs such as entire files or long logs, write the content to a file and ask Claude to read it instead of pasting. This keeps the conversation transcript readable and lets Claude reference the file by path in later turns.
worktrees+1-1
@@ -171,7 +171,7 @@ See the [Git worktree documentation](https://git-scm.com/docs/git-worktree) for
Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](/en/hooks#worktreecreate) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, [`.worktreeinclude`](#copy-gitignored-files-into-worktrees) is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead.
This `WorktreeCreate` hook reads the worktree name from stdin, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session's working directory:
This `WorktreeCreate` hook reads the worktree name from stdin, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session's working directory. Add the configuration to your [`settings.json`](/en/settings#settings-files):
```json
{