chore: update claude-api skill [auto-sync] (#729)

co-sign

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
cc-skill-sync[bot]
2026-03-22 12:16:01 -04:00
committed by GitHub
parent b0cbd3df15
commit 887114fd09
24 changed files with 1625 additions and 169 deletions
+81 -5
View File
@@ -115,8 +115,7 @@ Permission modes:
- `"default"`: Prompt for dangerous operations
- `"plan"`: Planning only, no execution
- `"acceptEdits"`: Auto-accept file edits
- `"dontAsk"`: Don't prompt (useful for CI/CD)
- `"bypassPermissions"`: Skip all prompts (requires `allow_dangerously_skip_permissions=True` in options)
- `"bypassPermissions"`: Skip all prompts (use with caution)
---
@@ -164,7 +163,9 @@ async for message in query(
print(message.result)
```
Available hook events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Notification`, `UserPromptSubmit`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStart`, `SubagentStop`, `PreCompact`, `PermissionRequest`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`
Hook callback inputs for tool-lifecycle events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`) include `agent_id` and `agent_type` fields, allowing hooks to identify which agent (main or subagent) triggered the tool call.
Available hook events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit`, `Stop`, `SubagentStop`, `PreCompact`, `Notification`, `SubagentStart`, `PermissionRequest`
---
@@ -183,7 +184,6 @@ async for message in query(prompt="...", options=ClaudeAgentOptions(...)):
| `tools` | list | Built-in tools to make available (restricts the default set) |
| `disallowed_tools` | list | Tools to explicitly disallow |
| `permission_mode` | string | How to handle permission prompts |
| `allow_dangerously_skip_permissions`| bool | Must be `True` to use `permission_mode="bypassPermissions"` |
| `mcp_servers` | dict | MCP servers to connect to |
| `hooks` | dict | Hooks for customizing behavior |
| `system_prompt` | string | Custom system prompt |
@@ -210,8 +210,26 @@ async for message in query(
):
if isinstance(message, ResultMessage):
print(message.result)
print(f"Stop reason: {message.stop_reason}") # e.g., "end_turn", "max_turns"
elif isinstance(message, SystemMessage) and message.subtype == "init":
session_id = message.session_id # Capture for resuming later
session_id = message.data.get("session_id") # Capture for resuming later
```
Typed task message subclasses are available for better type safety when handling subagent task events:
- `TaskStartedMessage` — emitted when a subagent task is registered
- `TaskProgressMessage` — real-time progress updates with cumulative usage metrics
- `TaskNotificationMessage` — task completion notifications
`RateLimitEvent` is emitted when the rate limit status transitions (e.g., from `allowed` to `allowed_warning` or `rejected`). Use it to warn users or back off gracefully:
```python
from claude_agent_sdk import query, ClaudeAgentOptions, RateLimitEvent
async for message in query(prompt="...", options=ClaudeAgentOptions()):
if isinstance(message, RateLimitEvent):
print(f"Rate limit status: {message.rate_limit_info.status}")
if message.rate_limit_info.resets_at:
print(f"Resets at: {message.rate_limit_info.resets_at}")
```
---
@@ -260,6 +278,64 @@ except CLIConnectionError as e:
---
## Session History
Retrieve past session data with top-level functions:
```python
from claude_agent_sdk import list_sessions, get_session_messages
# List all past sessions (sync function — no await)
sessions = list_sessions()
for session in sessions:
print(f"{session.session_id}: {session.cwd}")
# Get messages from a specific session (sync function — no await)
messages = get_session_messages(session_id="...")
for msg in messages:
print(msg)
```
### Session Mutations
Rename or tag sessions (sync functions — no await):
```python
from claude_agent_sdk import rename_session, tag_session
# Rename a session
rename_session(session_id="...", title="My refactoring session")
# Tag a session (tags are Unicode-sanitized automatically)
tag_session(session_id="...", tag="experiment")
# Clear a tag
tag_session(session_id="...", tag=None)
# Optionally scope to a specific project directory
rename_session(session_id="...", title="New title", directory="/path/to/project")
```
---
## MCP Server Management
Manage MCP servers at runtime using `ClaudeSDKClient`:
```python
async with ClaudeSDKClient(options=options) as client:
# Reconnect a disconnected MCP server
await client.reconnect_mcp_server("my-server")
# Toggle an MCP server on/off
await client.toggle_mcp_server("my-server", enabled=False)
# Get status of all MCP servers
status = await client.get_mcp_status() # returns McpStatusResponse
```
---
## Best Practices
1. **Always specify allowed_tools** — Explicitly list which tools the agent can use
+44 -4
View File
@@ -24,7 +24,7 @@ anyio.run(main)
## Custom Tools
Custom tools require an MCP server. Use `ClaudeSDKClient` for full control, or pass the server to `query()` via `mcp_servers`.
Custom tools require an MCP server. Use `ClaudeSDKClient` for full control (custom SDK MCP tools require `ClaudeSDKClient``query()` only supports external stdio/http MCP servers).
```python
import anyio
@@ -216,8 +216,7 @@ async def main():
prompt="Set up the development environment",
options=ClaudeAgentOptions(
allowed_tools=["Bash", "Write"],
permission_mode="bypassPermissions",
allow_dangerously_skip_permissions=True
permission_mode="bypassPermissions"
)
):
pass
@@ -278,7 +277,7 @@ async def main():
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"])
):
if isinstance(message, SystemMessage) and message.subtype == "init":
session_id = message.session_id
session_id = message.data.get("session_id")
# Resume with full context from the first query
async for message in query(
@@ -293,6 +292,47 @@ anyio.run(main)
---
## Session History
```python
from claude_agent_sdk import list_sessions, get_session_messages
# List past sessions (sync function — no await)
sessions = list_sessions()
for session in sessions:
print(f"Session {session.session_id} in {session.cwd}")
# Retrieve messages from the most recent session (sync function — no await)
if sessions:
messages = get_session_messages(session_id=sessions[0].session_id)
for msg in messages:
print(msg)
```
---
## Session Mutations
```python
from claude_agent_sdk import rename_session, tag_session
session_id = "your-session-id"
# Rename a session
rename_session(session_id=session_id, title="Refactoring auth module")
# Tag a session for filtering
tag_session(session_id=session_id, tag="experiment-v2")
# Clear a tag
tag_session(session_id=session_id, tag=None)
# Scope to a specific project directory
rename_session(session_id=session_id, title="New title", directory="/path/to/project")
```
---
## Custom System Prompt
```python
+21 -15
View File
@@ -28,12 +28,16 @@ async_client = anthropic.AsyncAnthropic()
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response.content[0].text)
# response.content is a list of content block objects (TextBlock, ThinkingBlock,
# ToolUseBlock, ...). Check .type before accessing .text.
for block in response.content:
if block.type == "text":
print(block.text)
```
---
@@ -43,7 +47,7 @@ print(response.content[0].text)
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
system="You are a helpful coding assistant. Always provide examples in Python.",
messages=[{"role": "user", "content": "How do I read a JSON file?"}]
)
@@ -63,7 +67,7 @@ with open("image.png", "rb") as f:
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": [
@@ -86,7 +90,7 @@ response = client.messages.create(
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": [
@@ -116,7 +120,7 @@ Use top-level `cache_control` to automatically cache the last cacheable block in
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
cache_control={"type": "ephemeral"}, # auto-caches the last cacheable block
system="You are an expert on this large document...",
messages=[{"role": "user", "content": "Summarize the key points"}]
@@ -130,7 +134,7 @@ For fine-grained control, add `cache_control` to specific content blocks:
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
system=[{
"type": "text",
"text": "You are an expert on this large document...",
@@ -142,7 +146,7 @@ response = client.messages.create(
# With explicit TTL (time-to-live)
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
system=[{
"type": "text",
"text": "You are an expert on this large document...",
@@ -228,13 +232,15 @@ class ConversationManager:
response = self.client.messages.create(
model=self.model,
max_tokens=kwargs.get("max_tokens", 1024),
max_tokens=kwargs.get("max_tokens", 16000),
system=self.system,
messages=self.messages,
**kwargs
)
assistant_message = response.content[0].text
assistant_message = next(
(b.text for b in response.content if b.type == "text"), ""
)
self.messages.append({"role": "assistant", "content": assistant_message})
return assistant_message
@@ -259,7 +265,7 @@ response2 = conversation.send("What's my name?") # Claude remembers "Alice"
### Compaction (long conversations)
> **Beta, Opus 4.6 only.** When conversations approach the 200K context window, compaction automatically summarizes earlier context server-side. The API returns a `compaction` block; you must pass it back on subsequent requests — append `response.content`, not just the text.
> **Beta, Opus 4.6 and Sonnet 4.6.** When conversations approach the 200K context window, compaction automatically summarizes earlier context server-side. The API returns a `compaction` block; you must pass it back on subsequent requests — append `response.content`, not just the text.
```python
import anthropic
@@ -273,7 +279,7 @@ def chat(user_message: str) -> str:
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
messages=messages,
context_management={
"edits": [{"type": "compact_20260112"}]
@@ -316,7 +322,7 @@ The `stop_reason` field in the response indicates why the model stopped generati
# Automatic caching (simplest — caches the last cacheable block)
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
cache_control={"type": "ephemeral"},
system=large_document_text, # e.g., 50KB of context
messages=[{"role": "user", "content": "Summarize the key points"}]
@@ -332,14 +338,14 @@ response = client.messages.create(
# Default to Opus for most tasks
response = client.messages.create(
model="claude-opus-4-6", # $5.00/$25.00 per 1M tokens
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Explain quantum computing"}]
)
# Use Sonnet for high-volume production workloads
standard_response = client.messages.create(
model="claude-sonnet-4-6", # $3.00/$15.00 per 1M tokens
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Summarize this document"}]
)
@@ -27,7 +27,7 @@ message_batch = client.messages.batches.create(
custom_id="request-1",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Summarize climate change impacts"}]
)
),
@@ -35,7 +35,7 @@ message_batch = client.messages.batches.create(
custom_id="request-2",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Explain quantum computing basics"}]
)
),
@@ -75,7 +75,9 @@ print(f"Errored: {batch.request_counts.errored}")
for result in client.messages.batches.results(message_batch.id):
match result.result.type:
case "succeeded":
print(f"[{result.custom_id}] {result.result.message.content[0].text[:100]}")
msg = result.result.message
text = next((b.text for b in msg.content if b.type == "text"), "")
print(f"[{result.custom_id}] {text[:100]}")
case "errored":
if result.result.error.type == "invalid_request":
print(f"[{result.custom_id}] Validation error - fix request and retry")
@@ -116,7 +118,7 @@ message_batch = client.messages.batches.create(
custom_id=f"analysis-{i}",
params=MessageCreateParamsNonStreaming(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
system=shared_system,
messages=[{"role": "user", "content": question}]
)
@@ -175,7 +177,8 @@ while True:
results = {}
for result in client.messages.batches.results(batch.id):
if result.result.type == "succeeded":
results[result.custom_id] = result.result.message.content[0].text
msg = result.result.message
results[result.custom_id] = next((b.text for b in msg.content if b.type == "text"), "")
for custom_id, classification in sorted(results.items()):
print(f"{custom_id}: {classification}")
@@ -37,7 +37,7 @@ print(f"Size: {uploaded.size_bytes} bytes")
```python
response = client.beta.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": [
@@ -52,7 +52,9 @@ response = client.beta.messages.create(
}],
betas=["files-api-2025-04-14"],
)
print(response.content[0].text)
for block in response.content:
if block.type == "text":
print(block.text)
```
### Image
@@ -64,7 +66,7 @@ image_file = client.beta.files.upload(
response = client.beta.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": [
@@ -141,7 +143,7 @@ questions = [
for question in questions:
response = client.beta.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": [
@@ -155,7 +157,8 @@ for question in questions:
betas=["files-api-2025-04-14"],
)
print(f"\nQ: {question}")
print(f"A: {response.content[0].text[:200]}")
text = next((b.text for b in response.content if b.type == "text"), "")
print(f"A: {text[:200]}")
# 3. Clean up when done
client.beta.files.delete(uploaded.id)
@@ -5,7 +5,7 @@
```python
with client.messages.stream(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=64000,
messages=[{"role": "user", "content": "Write a story"}]
) as stream:
for text in stream.text_stream:
@@ -17,7 +17,7 @@ with client.messages.stream(
```python
async with async_client.messages.stream(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=64000,
messages=[{"role": "user", "content": "Write a story"}]
) as stream:
async for text in stream.text_stream:
@@ -35,7 +35,7 @@ Claude may return text, thinking blocks, or tool use. Handle each appropriately:
```python
with client.messages.stream(
model="claude-opus-4-6",
max_tokens=16000,
max_tokens=64000,
thinking={"type": "adaptive"},
messages=[{"role": "user", "content": "Analyze this problem"}]
) as stream:
@@ -62,7 +62,7 @@ The Python tool runner currently returns complete messages. Use streaming for in
```python
with client.messages.stream(
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=64000,
tools=tools,
messages=messages
) as stream:
@@ -80,7 +80,7 @@ with client.messages.stream(
```python
with client.messages.stream(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=64000,
messages=[{"role": "user", "content": "Hello"}]
) as stream:
for text in stream.text_stream:
@@ -127,7 +127,7 @@ def stream_with_progress(client, **kwargs):
try:
with client.messages.stream(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=64000,
messages=[{"role": "user", "content": "Write a story"}]
) as stream:
for text in stream.text_stream:
+24 -21
View File
@@ -28,7 +28,7 @@ def get_weather(location: str, unit: str = "celsius") -> str:
# The tool runner handles the agentic loop automatically
runner = client.beta.messages.tool_runner(
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
tools=[get_weather],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
@@ -70,9 +70,10 @@ async with stdio_client(StdioServerParameters(command="mcp-server")) as (read, w
await mcp_client.initialize()
tools_result = await mcp_client.list_tools()
runner = await client.beta.messages.tool_runner(
# tool_runner is sync — returns the runner, not a coroutine
runner = client.beta.messages.tool_runner(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Use the available tools"}],
tools=[async_mcp_tool(t, mcp_client) for t in tools_result.tools],
)
@@ -90,7 +91,7 @@ from anthropic.lib.tools.mcp import mcp_message
prompt = await mcp_client.get_prompt(name="my-prompt")
response = await client.beta.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[mcp_message(m) for m in prompt.messages],
)
```
@@ -103,7 +104,7 @@ from anthropic.lib.tools.mcp import mcp_resource_to_content
resource = await mcp_client.read_resource(uri="file:///path/to/doc.txt")
response = await client.beta.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": [
@@ -142,7 +143,7 @@ messages = [{"role": "user", "content": user_input}]
while True:
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
tools=tools,
messages=messages
)
@@ -189,7 +190,7 @@ final_text = next(b.text for b in response.content if b.type == "text")
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Paris?"}]
)
@@ -204,7 +205,7 @@ for block in response.content:
followup = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Paris?"},
@@ -241,7 +242,7 @@ for block in response.content:
if tool_results:
followup = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
tools=tools,
messages=[
*previous_messages,
@@ -271,7 +272,7 @@ tool_result = {
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
tools=tools,
tool_choice={"type": "tool", "name": "get_weather"}, # Force specific tool
messages=[{"role": "user", "content": "What's the weather in Paris?"}]
@@ -291,7 +292,7 @@ client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
messages=[{
"role": "user",
"content": "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
@@ -319,7 +320,7 @@ uploaded = client.beta.files.upload(file=open("sales_data.csv", "rb"))
# Code execution is GA; Files API is still beta (pass via extra_headers)
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
extra_headers={"anthropic-beta": "files-api-2025-04-14"},
messages=[{
"role": "user",
@@ -364,7 +365,7 @@ for block in response.content:
# First request: set up environment
response1 = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
messages=[{"role": "user", "content": "Install tabulate and create data.json with sample data"}],
tools=[{"type": "code_execution_20260120", "name": "code_execution"}]
)
@@ -376,7 +377,7 @@ container_id = response1.container.id
response2 = client.messages.create(
container=container_id,
model="claude-opus-4-6",
max_tokens=4096,
max_tokens=16000,
messages=[{"role": "user", "content": "Read data.json and display as a formatted table"}],
tools=[{"type": "code_execution_20260120", "name": "code_execution"}]
)
@@ -416,7 +417,7 @@ client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=2048,
max_tokens=16000,
messages=[{"role": "user", "content": "Remember that my preferred language is Python."}],
tools=[{"type": "memory_20250818", "name": "memory"}],
)
@@ -442,7 +443,7 @@ memory = MyMemoryTool()
# Use with tool runner
runner = client.beta.messages.tool_runner(
model="claude-opus-4-6",
max_tokens=2048,
max_tokens=16000,
tools=[memory],
messages=[{"role": "user", "content": "Remember my preferences"}],
)
@@ -477,7 +478,7 @@ client = anthropic.Anthropic()
response = client.messages.parse(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": "Extract: Jane Doe (jane@co.com) wants Enterprise, interested in API and SDKs, wants a demo."
@@ -496,7 +497,7 @@ print(contact.interests) # ["API", "SDKs"]
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{
"role": "user",
"content": "Extract info: John Smith (john@example.com) wants the Enterprise plan."
@@ -520,7 +521,9 @@ response = client.messages.create(
)
import json
data = json.loads(response.content[0].text)
# output_config.format guarantees the first block is text with valid JSON
text = next(b.text for b in response.content if b.type == "text")
data = json.loads(text)
```
### Strict Tool Use
@@ -528,7 +531,7 @@ data = json.loads(response.content[0].text)
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Book a flight to Tokyo for 2 passengers on March 15"}],
tools=[{
"name": "book_flight",
@@ -553,7 +556,7 @@ response = client.messages.create(
```python
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
max_tokens=16000,
messages=[{"role": "user", "content": "Plan a trip to Paris next month"}],
output_config={
"format": {