### Quick Start: Connecting to Claude Code Docs MCP Server
Source: https://platform.claude.com/docs/zh-CN/agent-sdk/mcp
This example demonstrates connecting to the Claude Code documentation MCP server using HTTP transport and allowing all tools with a wildcard.
```APIDOC
## GET /query (Example)
### Description
This example shows how to use the `query` function from the `@anthropic-ai/claude-agent-sdk` to connect to an MCP server and retrieve information.
### Method
POST
### Endpoint
/query
### Parameters
#### Query Parameters
- **prompt** (string) - Required - The prompt to send to the agent.
- **options** (object) - Optional - Configuration options for the query.
- **mcpServers** (object) - A map of MCP server configurations.
- **claude-code-docs** (object) - Configuration for the Claude Code docs server.
- **type** (string) - Required - The transport type, e.g., 'http'.
- **url** (string) - Required - The URL of the MCP server.
- **allowedTools** (array) - Optional - A list of tool names that the agent is allowed to use.
- **item** (string) - The name of the allowed tool, e.g., 'mcp__claude-code-docs__*'.
### Request Example
```typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Use the docs MCP server to explain what hooks are in Claude Code",
options: {
mcpServers: {
"claude-code-docs": {
type: "http",
url: "https://code.claude.com/docs/mcp"
}
},
allowedTools: ["mcp__claude-code-docs__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
```
```python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
"claude-code-docs": {
"type": "http",
"url": "https://code.claude.com/docs/mcp"
}
},
allowed_tools=["mcp__claude-code-docs__*"]
)
async for message in query(prompt="Use the docs MCP server to explain what hooks are in Claude Code", options=options):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
```
### Response
#### Success Response (200)
- **type** (string) - The type of message received (e.g., 'result', 'system').
- **subtype** (string) - The subtype of the message (e.g., 'success', 'error', 'init').
- **result** (any) - The result of the tool execution if the subtype is 'success'.
#### Response Example
```json
{
"type": "result",
"subtype": "success",
"result": "Hooks in Claude Code are special functions that allow you to intercept and modify behavior at specific points in the code execution lifecycle..."
}
```
```
--------------------------------
### Providing Tool Use Examples (Beta)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/implement-tool-use
Information on how to provide example inputs for tools, a beta feature.
```APIDOC
## Providing Tool Use Examples (Beta)
You can provide specific examples of valid tool inputs to help Claude understand how to use your tools more effectively. This is particularly useful for complex tools with nested objects, optional parameters, or format-sensitive inputs.
### Beta Headers
Tool use examples are a beta feature. Ensure you include the appropriate beta headers for your provider:
| Provider | Beta Header |
|-----------------|---------------------------|
| Claude API,
Microsoft Foundry | `advanced-tool-use-2025-11-20` |
| Vertex AI,
Amazon Bedrock | `tool-examples-2025-10-29` |
Supported Models:
- Claude API, Microsoft Foundry: All models
- Vertex AI, Amazon Bedrock: Claude Opus 4.6, Claude Opus 4.5
```
--------------------------------
### Skill Resource Structure Example (File System)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/agent-skills/overview
This illustrates the file system structure of a Skill, showing how instructions, guides, reference materials, and executable scripts can be organized. This hierarchical structure allows for modularity and efficient on-demand loading of specific resources or code when needed.
```file-system
pdf-skill/
├── SKILL.md (main instructions)
├── FORMS.md (form-filling guide)
├── REFERENCE.md (detailed API reference)
└── scripts/
└── fill_form.py (utility script)
```
--------------------------------
### Good Tool Description Example
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/implement-tool-use
An example of a well-written tool description for retrieving stock prices.
```APIDOC
## Good Tool Description Example
This is an example of a good tool description:
### Request Body
```json
{
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}
```
```
--------------------------------
### Tool Use Code Examples
Source: https://platform.claude.com/docs/zh-CN/build-with-claude/tool-use
Explore practical code examples in the cookbook to implement tool usage with Claude.
```APIDOC
## Tool Use Code Examples
### Description
This section provides links to practical code examples demonstrating how to integrate tool usage with Claude.
### Examples
* **Calculator Tool:** Learn how to integrate a simple calculator tool for precise numerical computations.
* **Customer Service Agent:** Build a responsive customer service bot enhanced with client-side tools.
* **JSON Extractor:** Discover how Claude and tool usage can extract structured data from unstructured text.
```
--------------------------------
### List GitHub Issues using Claude Agent SDK (TypeScript, Python)
Source: https://platform.claude.com/docs/zh-CN/agent-sdk/mcp
This example demonstrates connecting to a GitHub MCP server to list recent issues. It includes setup instructions for a GitHub token and environment variables. Debugging logs are provided to verify MCP connection and tool usage, facilitating troubleshooting.
```typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "List the 3 most recent issues in anthropics/claude-code",
options: {
mcpServers: {
"github": {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-github"],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
},
allowedTools: ["mcp__github__list_issues"]
}
})) {
// 验证 MCP 服务器连接成功
if (message.type === "system" && message.subtype === "init") {
console.log("MCP servers:", message.mcp_servers);
}
// 记录 Claude 调用 MCP 工具的时间
if (message.type === "assistant") {
for (const block of message.content) {
if (block.type === "tool_use" && block.name.startsWith("mcp__")) {
console.log("MCP tool called:", block.name);
}
}
}
// 打印最终结果
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
```
```python
import asyncio
import os
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage, AssistantMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]
}
}
},
allowed_tools=["mcp__github__list_issues"]
)
async for message in query(prompt="List the 3 most recent issues in anthropics/claude-code", options=options):
# 验证 MCP 服务器连接成功
if isinstance(message, SystemMessage) and message.subtype == "init":
print("MCP servers:", message.data.get("mcp_servers"))
# 记录 Claude 调用 MCP 工具的时间
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "name") and block.name.startswith("mcp__"):
print("MCP tool called:", block.name)
# 打印最终结果
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
```
--------------------------------
### Bad Tool Description Example
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/implement-tool-use
An example of a poorly written tool description for retrieving stock prices.
```APIDOC
## Bad Tool Description Example
This is an example of a bad tool description:
### Request Body
```json
{
"name": "get_stock_price",
"description": "Gets the stock price for a ticker.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string"
}
},
"required": ["ticker"]
}
}
```
A poor description is too brief, leaving Claude with many questions about the tool's behavior and usage.
```
--------------------------------
### Create File Command Example (JSON)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/text-editor-tool
This JSON example demonstrates the 'create' command for the text editor tool. It allows Claude to create a new file at a specified path with provided content.
```json
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_editor",
"input": {
"command": "create",
"path": "test_primes.py",
"file_text": "import unittest\nimport primes\n\nclass TestPrimes(unittest.TestCase):\n def test_is_prime(self):\n self.assertTrue(primes.is_prime(2))\n self.assertTrue(primes.is_prime(3))\n self.assertFalse(primes.is_prime(4))\n\nif __name__ == '__main__':\n unittest.main()"
}
}
```
--------------------------------
### Simple Tool Definition Example
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/implement-tool-use
An example of a simple tool definition for getting weather information.
```APIDOC
## Simple Tool Definition Example
This is an example of a simple tool definition:
### Request Body
```json
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
}
},
"required": ["location"]
}
}
```
This `get_weather` tool expects an input object with a required `location` string and an optional `unit` string, which must be either 'celsius' or 'fahrenheit'.
```
--------------------------------
### Skill Instructions Example (Markdown with Python)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/agent-skills/overview
This example demonstrates the main instructions within a Skill's SKILL.md file. It includes procedural knowledge, best practices, and code snippets. This content is loaded into the context window only when the Skill is triggered by a user request matching its description.
```markdown
# PDF Processing
## Quick start
Use pdfplumber to extract text from PDFs:
```python
import pdfplumber
with pdfplumber.open("document.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
For advanced form filling, see [FORMS.md](FORMS.md).
```
--------------------------------
### POST /v1/messages - Tool Use Example (Java)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/overview
This Java example outlines the setup for using the Anthropic Java SDK to interact with tools.
```APIDOC
## POST /v1/messages - Tool Use Example (Java)
### Description
This Java example outlines the setup for using the Anthropic Java SDK to interact with tools.
### Method
POST
### Endpoint
https://api.anthropic.com/v1/messages
### Parameters
#### Request Body (via SDK)
- **model** (String) - Required - The model to use, e.g., "claude-opus-4-6".
- **max_tokens** (Integer) - Required - The maximum number of tokens to generate.
- **tools** (List) - Required - A list of tool definitions.
- **name** (String) - Required - The name of the tool.
- **description** (String) - Required - A description of what the tool does.
- **inputSchema** (InputSchema) - Required - The JSON schema for the tool's input.
- **type** (String) - Required - Must be "object".
- **properties** (Map) - Required - Defines the properties of the input.
- **location** (Property) - Required -
- **type** (String) - Required - Must be "string".
- **description** (String) - Required - The city and state, e.g. San Francisco, CA.
- **unit** (Property) - Optional -
- **type** (String) - Required - Must be "string".
- **enum** (List) - Required - Allowed values: ["celsius", "fahrenheit"].
- **description** (String) - The unit of temperature, either "celsius" or "fahrenheit".
- **required** (List) - Required - List of required properties, e.g., ["location"].
- **messages** (List) - Required - The conversation history.
- **role** (String) - Required - The role of the message sender (e.g., "user", "assistant").
- **content** (List) - Required - The content of the message.
- ContentBlock can be of type TextBlock, ToolUseBlock, or ToolResultBlock.
- **TextBlock**: requires `text` (String).
- **ToolUseBlock**: requires `id` (String), `name` (String), `input` (JsonValue).
- **ToolResultBlock**: requires `tool_use_id` (String), `content` (String).
### Request Example
```java
import java.util.List;
import java.util.Map;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.*;
import com.anthropic.models.messages.Tool.InputSchema;
public class ToolConversationExample {
public static void main(String[] args) {
// Initialize the client
AnthropicClient client = AnthropicOkHttpClient.builder()
.apiKey("YOUR_ANTHROPIC_API_KEY") // Replace with your API key
.build();
// Define the tool schema
Tool getWeatherTool = Tool.builder()
.name("get_weather")
.description("Get the current weather in a given location")
.inputSchema(InputSchema.builder()
.type("object")
.properties(Map.of(
"location", new Tool.Property("string", "The city and state, e.g. San Francisco, CA", null, null),
"unit", new Tool.Property("string", "The unit of temperature, either \"celsius\" or \"fahrenheit\"", List.of("celsius", "fahrenheit"), null)
))
.required(List.of("location"))
.build())
.build();
// Construct the messages list
List messages = List.of(
new Message("user", List.of(new TextBlock("What's the weather like in San Francisco?"))),
new Message("assistant", List.of(
new TextBlock("I'll check the current weather in San Francisco for you."),
new ToolUseBlock("toolu_01A09q90qw90lq917835lq9", "get_weather", JsonValue.fromJson("{\"location\": \"San Francisco, CA\", \"unit\": \"celsius\"}"))
)),
new Message("user", List.of(
new ToolResultBlock("toolu_01A09q90qw90lq917835lq9", "15 degrees")
))
);
// Create the request
MessagesRequest request = MessagesRequest.builder()
.model("claude-opus-4-6")
.maxTokens(1024)
.tools(List.of(getWeatherTool))
.messages(messages)
.build();
// Send the request and get the response
MessagesResponse response = client.messages.create(request);
// Process the response
System.out.println(response);
}
}
```
### Response
#### Success Response (200)
- **id** (String) - The ID of the message.
- **type** (String) - The type of the message, e.g., "message".
- **role** (String) - The role of the sender, e.g., "assistant".
- **content** (List) - The content of the message, which can include text and tool results.
- **model** (String) - The model used for generation.
- **stopReason** (String) - The reason the model stopped generating.
- **stopSequence** (String or null) - The stop sequence, if any.
- **usage** (Usage) - Information about token usage.
- **inputTokens** (Integer) - The number of input tokens.
- **outputTokens** (Integer) - The number of output tokens.
#### Response Example
```java
// Assuming 'response' is the MessagesResponse object
System.out.println(response.getContent());
// Example output:
// [TextBlock(text='The weather in San Francisco is 15 degrees Celsius.', type='text')]
```
```
--------------------------------
### Basic Streaming Request Example (Server-Sent Events)
Source: https://platform.claude.com/docs/zh-CN/claude_api_primer
An example of Server-Sent Events (SSE) for a streaming response, showing the sequence of events including message start, content blocks, deltas, and message stop.
```sse
event: message_start
data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-6", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}
event: content_block_stop
data: {"type": "content_block_stop", "index": 0}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}
event: message_stop
data: {"type": "message_stop"}
```
--------------------------------
### View File or Directory Command Example (JSON)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/text-editor-tool
This JSON example shows the structure for the 'view' command used with the text editor tool. It can be used to inspect the content of a specific file or list the contents of a directory.
```json
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_editor",
"input": {
"command": "view",
"path": "primes.py"
}
}
{
"type": "tool_use",
"id": "toolu_02B19r91rw91mr917835mr9",
"name": "str_replace_editor",
"input": {
"command": "view",
"path": "src/"
}
}
```
--------------------------------
### Single Tool Example: Get Weather
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/overview
Demonstrates how to define and use a 'get_weather' tool with Claude. This example shows the request structure for calling the tool with specified parameters like location and unit. It's applicable for shell, Python, and Java.
```bash
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"tools": [{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either \"celsius\" or \"fahrenheit\""
}
},
"required": ["location"]
}
}],
"messages": [{"role": "user", "content": "What is the weather like in San Francisco?"}]
}'
```
```python
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
tools=[
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either \"celsius\" or \"fahrenheit\""
}
},
"required": ["location"]
}
}
],
messages=[{"role": "user", "content": "What is the weather like in San Francisco?"}]
)
print(response)
```
```java
import java.util.List;
import java.util.Map;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.Tool;
import com.anthropic.models.messages.Tool.InputSchema;
public class WeatherToolExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
InputSchema schema = InputSchema.builder()
.properties(JsonValue.from(Map.of(
"location", Map.of(
"type", "string",
"description", "The city and state, e.g. San Francisco, CA"
),
"unit", Map.of(
"type", "string",
"enum", List.of("celsius", "fahrenheit"),
"description", "The unit of temperature, either \"celsius\" or \"fahrenheit\""
)
)))
.putAdditionalProperty("required", JsonValue.from(List.of("location")))
.build();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.addTool(Tool.builder()
.name("get_weather")
.description("Get the current weather in a given location")
.inputSchema(schema)
.build())
.addUserMessage("What is the weather like in San Francisco?")
.build();
Message message = client.messages().create(params);
System.out.println(message);
}
}
```
--------------------------------
### Sequential Tool Calls with cURL
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/overview
Shows an example of using cURL to interact with the Anthropic API for sequential tool calls. The scenario involves getting the user's location first using 'get_location', and then using that location to get the weather via 'get_weather'.
```bash
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"tools": [
{
"name": "get_location",
"description": "Get the current user location based on their IP address. This tool has no parameters or arguments.",
"input_schema": {
"type": "object",
"properties": {}
}
},
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
}
},
"required": ["location"]
}
}
],
"messages": [{
"role": "user",
"content": "What is the weather like where I am?"
}]
}'
```
--------------------------------
### Pre-filling Claude's Response
Source: https://platform.claude.com/docs/zh-CN/claude_api_primer
Example of pre-filling Claude's response to guide its output, useful for constrained responses like multiple-choice.
```APIDOC
## Pre-filling Claude's Response
Partially pre-fill Claude's response by including an 'assistant' message at the end of the `messages` array.
### Request Example
```python
message = anthropic.Anthropic().messages.create(
model="claude-opus-4-6",
max_tokens=1,
messages=[
{"role": "user", "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"},
{"role": "assistant", "content": "The answer is ("}
]
)
```
```
--------------------------------
### Define Tool with Input Examples (Python)
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/implement-tool-use
Demonstrates how to define a tool in Python with an `input_examples` field. This helps Claude understand the expected input format for tool calls. The example includes a 'get_weather' tool with a schema and sample inputs.
```python
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
betas=["advanced-tool-use-2025-11-20"],
tools=[
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature"
}
},
"required": ["location"]
},
"input_examples": [
{
"location": "San Francisco, CA",
"unit": "fahrenheit"
},
{
"location": "Tokyo, Japan",
"unit": "celsius"
},
{
"location": "New York, NY" # 'unit' is optional
}
]
}
],
messages=[
{"role": "user", "content": "What's the weather like in San Francisco?"}
]
)
```
--------------------------------
### Quick Start Example - TypeScript
Source: https://platform.claude.com/docs/zh-CN/api/openai-sdk
Demonstrates how to initialize the OpenAI SDK client for the Claude API and make a chat completion request in TypeScript.
```APIDOC
## POST /v1/chat/completions (OpenAI SDK Compatibility)
### Description
This endpoint allows you to use the OpenAI SDK to interact with the Claude API by configuring the client with Claude's API key and endpoint.
### Method
POST
### Endpoint
/v1/chat/completions
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **model** (string) - Required - The Claude model name to use (e.g., "claude-opus-4-6").
- **messages** (array) - Required - A list of message objects, where each object has a `role` (user) and `content` (string).
- **max_tokens** (integer) - Optional - The maximum number of tokens to generate.
- **temperature** (number) - Optional - Controls randomness. Value between 0 and 1.
- **stream** (boolean) - Optional - Whether to stream the response.
- **stream_options** (object) - Optional - Options for streaming.
- **top_p** (number) - Optional - Nucleus sampling parameter.
- **parallel_tool_calls** (boolean) - Optional - Whether to allow parallel tool calls.
- **stop** (string or array) - Optional - Sequences where the API will stop generating further tokens.
- **thinking** (object) - Optional - Enables extended thinking for complex tasks. Requires native Claude API for full output.
### Request Example
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: "ANTHROPIC_API_KEY", // Your Claude API key
baseURL: "https://api.anthropic.com/v1/", // Claude API endpoint
});
const response = await openai.chat.completions.create({
messages: [
{ role: "user", content: "Who are you?" }
],
model: "claude-opus-4-6", // Claude model name
});
console.log(response.choices[0].message.content);
```
### Response
#### Success Response (200)
- **choices** (array) - A list of message choices.
- **message** (object)
- **role** (string) - The role of the message sender (e.g., "assistant").
- **content** (string) - The content of the message.
#### Response Example
```json
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "I am a large language model, trained by Anthropic."
}
],
"model": "claude-opus-4-6",
"stop_reason": "end_turn",
"stop_sequence": null
}
```
```
--------------------------------
### Python Example: Using Tool Search with Prompt Caching
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/tool-search-tool
This Python code demonstrates how to integrate Claude's tool search with prompt caching for optimized multi-turn conversations. It shows the initial request, appending the assistant's response, and a subsequent request with `cache_control` to leverage caching.
```python
import anthropic
client = anthropic.Anthropic()
# 带工具搜索的第一个请求
messages = [
{
"role": "user",
"content": "What's the weather in Seattle?"
}
]
response1 = client.beta.messages.create(
model="claude-opus-4-6",
betas=["advanced-tool-use-2025-11-20"],
max_tokens=2048,
messages=messages,
tools=[
{
"type": "tool_search_tool_regex_20251119",
"name": "tool_search_tool_regex"
},
{
"name": "get_weather",
"description": "Get weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
},
"defer_loading": True
}
]
)
# 将 Claude 的响应添加到对话中
messages.append({
"role": "assistant",
"content": response1.content
})
# 带缓存断点的第二个请求
messages.append({
"role": "user",
"content": "What about New York?",
"cache_control": {"type": "ephemeral"}
})
response2 = client.beta.messages.create(
model="claude-opus-4-6",
betas=["advanced-tool-use-2025-11-20"],
max_tokens=2048,
messages=messages,
tools=[
{
"type": "tool_search_tool_regex_20251119",
"name": "tool_search_tool_regex"
},
{
"name": "get_weather",
"description": "Get weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
},
"defer_loading": True
}
]
)
print(f"Cache read tokens: {response2.usage.get('cache_read_input_tokens', 0)}")
```
--------------------------------
### Run Interactive Example with Checkpointing (Python & TypeScript)
Source: https://platform.claude.com/docs/zh-CN/agent-sdk/file-checkpointing
An interactive script that uses the Claude Agent SDK to add documentation comments to a utility file. It demonstrates the full checkpointing workflow, allowing users to revert changes. Requires the Claude Agent SDK and configures options for file checkpointing and automatic edit acceptance.
```python
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, UserMessage, ResultMessage
async def main():
# 配置启用检查点的 SDK
# - enable_file_checkpointing:跟踪文件更改以便回退
# - permission_mode:自动接受文件编辑,无需提示
# - extra_args:需要此选项才能在流中接收用户消息 UUID
options = ClaudeAgentOptions(
enable_file_checkpointing=True,
permission_mode="acceptEdits",
extra_args={"replay-user-messages": None}
)
checkpoint_id = None # 存储用于回退的用户消息 UUID
session_id = None # 存储用于恢复的会话 ID
print("Running agent to add doc comments to utils.py...\n")
# 运行代理并从响应流中捕获检查点数据
async with ClaudeSDKClient(options) as client:
await client.query("Add doc comments to utils.py")
async for message in client.receive_response():
# 捕获第一条用户消息 UUID - 这是我们的恢复点
if isinstance(message, UserMessage) and message.uuid and not checkpoint_id:
checkpoint_id = message.uuid
# 捕获会话 ID 以便稍后恢复
if isinstance(message, ResultMessage):
session_id = message.session_id
print("Done! Open utils.py to see the added doc comments.\n")
# 询问用户是否要回退更改
if checkpoint_id and session_id:
response = input("Rewind to remove the doc comments? (y/n): ")
if response.lower() == "y":
# 使用空提示恢复会话,然后回退
async with ClaudeSDKClient(ClaudeAgentOptions(
enable_file_checkpointing=True,
resume=session_id
)) as client:
await client.query("") # 空提示打开连接
async for message in client.receive_response():
await client.rewind_files(checkpoint_id) # 恢复文件
break
print("\n✓ File restored! Open utils.py to verify the doc comments are gone.")
else:
print("\nKept the modified file.")
asyncio.run(main())
```
```typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
import * as readline from "readline";
async function main() {
// 配置启用检查点的 SDK
// - enableFileCheckpointing:跟踪文件更改以便回退
// - permissionMode:自动接受文件编辑,无需提示
// - extraArgs:需要此选项才能在流中接收用户消息 UUID
const opts = {
enableFileCheckpointing: true,
permissionMode: "acceptEdits" as const,
extraArgs: { 'replay-user-messages': null }
};
let sessionId: string | undefined;
let checkpointId: string | undefined;
console.log("Running agent to add doc comments to utils.ts...\n");
const response = query({
prompt: "Add doc comments to utils.ts",
options: opts
});
for await (const message of response) {
if (message.type === "user" && message.uuid && !checkpointId) {
checkpointId = message.uuid;
}
if ("session_id" in message) {
sessionId = message.session_id;
}
}
console.log("Done! Open utils.ts to see the added doc comments.\n");
if (checkpointId && sessionId) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const answer = await new Promise((resolve) => {
rl.question("Rewind to remove the doc comments? (y/n): ", resolve);
});
rl.close();
if (answer.toLowerCase() === "y") {
const rewindQuery = query({
prompt: "",
options: { ...opts, resume: sessionId }
});
for await (const msg of rewindQuery) {
await rewindQuery.rewindFiles(checkpointId);
break;
}
console.log("\n✓ File restored! Open utils.ts to verify the doc comments are gone.");
} else {
console.log("\nKept the modified file.");
}
}
}
main();
```
--------------------------------
### Quick Start Example - Python
Source: https://platform.claude.com/docs/zh-CN/api/openai-sdk
Demonstrates how to initialize the OpenAI SDK client for the Claude API and make a chat completion request in Python.
```APIDOC
## POST /v1/chat/completions (OpenAI SDK Compatibility)
### Description
This endpoint allows you to use the OpenAI SDK to interact with the Claude API by configuring the client with Claude's API key and endpoint.
### Method
POST
### Endpoint
/v1/chat/completions
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **model** (string) - Required - The Claude model name to use (e.g., "claude-opus-4-6").
- **messages** (array) - Required - A list of message objects, where each object has a `role` (system or user) and `content` (string).
- **system** (string) - Optional - A system prompt.
- **max_tokens** (integer) - Optional - The maximum number of tokens to generate.
- **temperature** (number) - Optional - Controls randomness. Value between 0 and 1.
- **stream** (boolean) - Optional - Whether to stream the response.
- **stream_options** (object) - Optional - Options for streaming.
- **top_p** (number) - Optional - Nucleus sampling parameter.
- **parallel_tool_calls** (boolean) - Optional - Whether to allow parallel tool calls.
- **stop** (string or array) - Optional - Sequences where the API will stop generating further tokens.
- **extra_body** (object) - Optional - For Claude-specific parameters like `thinking`.
### Request Example
```python
from openai import OpenAI
client = OpenAI(
api_key="ANTHROPIC_API_KEY", # Your Claude API key
base_url="https://api.anthropic.com/v1/" # the Claude API endpoint
)
response = client.chat.completions.create(
model="claude-opus-4-6", # Anthropic model name
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"}
],
)
print(response.choices[0].message.content)
```
### Response
#### Success Response (200)
- **choices** (array) - A list of message choices.
- **message** (object)
- **role** (string) - The role of the message sender (e.g., "assistant").
- **content** (string) - The content of the message.
#### Response Example
```json
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "I am a large language model, trained by Anthropic."
}
],
"model": "claude-opus-4-6",
"stop_reason": "end_turn",
"stop_sequence": null
}
```
```
--------------------------------
### Java: Use Text Editor Tool for Python Code Correction
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/text-editor-tool
This Java example shows how to use the Anthropic client library to interact with the `str_replace_based_edit_tool`. It constructs a message to Claude, including previous conversation turns and a tool use block to fix a syntax error in a Python file. The example highlights the setup for using tools within the Anthropic API.
```java
import java.util.List;
import java.util.Map;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.MessageParam;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.TextBlockParam;
import com.anthropic.models.messages.ToolResultBlockParam;
import com.anthropic.models.messages.ToolStrReplaceBasedEditTool20250728;
import com.anthropic.models.messages.ToolUseBlockParam;
public class TextEditorConversationExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_SONNET_4_0)
.maxTokens(1024)
.addTool(ToolStrReplaceBasedEditTool20250728.builder()
.build())
// 之前的消息放在这里
.addAssistantMessageOfBlockParams(
List.of(
ContentBlockParam.ofText(TextBlockParam.builder()
.text("I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you.")
.build()),
ContentBlockParam.ofToolUse(ToolUseBlockParam.builder()
.id("toolu_01PqRsTuVwXyZAbCdEfGh")
.name("str_replace_based_edit_tool")
.input(JsonValue.from(Map.of(
"command", "str_replace",
"path", "primes.py",
"old_str", " for num in range(2, limit + 1)",
"new_str", " for num in range(2, limit + 1):"
)))
.build()
)
)
)
.addUserMessageOfBlockParams(List.of(
ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()
.toolUseId("toolu_01PqRsTuVwXyZAbCdEfGh")
.content("Successfully replaced text at exactly one location.")
.build()
)
))
.build();
Message message = client.messages().create(params);
System.out.println(message);
}
}
```
--------------------------------
### Python:创建文件备份
Source: https://platform.claude.com/docs/zh-CN/agents-and-tools/tool-use/text-editor-tool
此 Python 函数用于在编辑文件之前创建其备份。它通过在原始文件路径后附加 '.backup' 来生成备份文件路径,并复制原始文件的内容。如果原始文件不存在,则不会执行任何操作。
```python
import os
def backup_file(file_path):
"""Create a backup of a file before editing."""
backup_path = f"{file_path}.backup"
if os.path.exists(file_path):
with open(file_path, 'r') as src, open(backup_path, 'w') as dst:
dst.write(src.read())
```