Loading...
Loading...
Compare original and translation side by side
undefinedundefinedundefinedundefinedfrom claude_agent_sdk import query
result = await query(
model="claude-sonnet-4-5",
system_prompt="You are a helpful coding assistant.",
user_message="List files in current directory",
working_dir=".",
)
print(result.final_message)from claude_agent_sdk import query
result = await query(
model="claude-sonnet-4-5",
system_prompt="You are a helpful coding assistant.",
user_message="List files in current directory",
working_dir=".",
)
print(result.final_message)import { ClaudeSdkClient } from '@anthropic-ai/agent-sdk';
const client = new ClaudeSdkClient({ apiKey: process.env.ANTHROPIC_API_KEY });
const result = await client.query({
model: 'claude-sonnet-4-5',
systemPrompt: 'You are a helpful coding assistant.',
userMessage: 'List files in current directory',
workingDir: '.',
});
console.log(result.finalMessage);import { ClaudeSdkClient } from '@anthropic-ai/agent-sdk';
const client = new ClaudeSdkClient({ apiKey: process.env.ANTHROPIC_API_KEY });
const result = await client.query({
model: 'claude-sonnet-4-5',
systemPrompt: 'You are a helpful coding assistant.',
userMessage: 'List files in current directory',
workingDir: '.',
});
console.log(result.finalMessage);from claude_agent_sdk.mcp import tool, create_sdk_mcp_server
@tool(
name="calculator",
description="Perform calculations",
input_schema={"expression": str}
)
async def calculator(args):
result = eval(args["expression"]) # Use safe eval in production
return {"content": [{"type": "text", "text": str(result)}]}
server = create_sdk_mcp_server(name="math", tools=[calculator])import { createSdkMcpServer, tool } from '@anthropic-ai/agent-sdk';
import { z } from 'zod';
const calculator = tool({
name: 'calculator',
description: 'Perform calculations',
inputSchema: z.object({ expression: z.string() }),
async execute({ expression }) {
const result = eval(expression); // Use safe eval in production
return { content: [{ type: 'text', text: String(result) }] };
},
});
const server = createSdkMcpServer({ name: 'math', tools: [calculator] });from claude_agent_sdk.mcp import tool, create_sdk_mcp_server
@tool(
name="calculator",
description="Perform calculations",
input_schema={"expression": str}
)
async def calculator(args):
result = eval(args["expression"]) # 生产环境请使用安全eval
return {"content": [{"type": "text", "text": str(result)}]}
server = create_sdk_mcp_server(name="math", tools=[calculator])import { createSdkMcpServer, tool } from '@anthropic-ai/agent-sdk';
import { z } from 'zod';
const calculator = tool({
name: 'calculator',
description: 'Perform calculations',
inputSchema: z.object({ expression: z.string() }),
async execute({ expression }) {
const result = eval(expression); // 生产环境请使用安全eval
return { content: [{ type: 'text', text: String(result) }] };
},
});
const server = createSdkMcpServer({ name: 'math', tools: [calculator] });PreToolUsePostToolUseStopasync def validate_command(input_data, tool_use_id, context):
if "rm -rf" in input_data["tool_input"].get("command", ""):
return {
"hookSpecificOutput": {
"permissionDecision": "deny",
"permissionDecisionReason": "Dangerous command blocked"
}
}const loggingHook = {
matcher: (input) => input.toolName === 'bash',
async handler(input, toolUseId, context) {
console.log(`Executing: ${input.toolInput.command}`);
}
};PreToolUsePostToolUseStopasync def validate_command(input_data, tool_use_id, context):
if "rm -rf" in input_data["tool_input"].get("command", ""):
return {
"hookSpecificOutput": {
"permissionDecision": "deny",
"permissionDecisionReason": "Dangerous command blocked"
}
}const loggingHook = {
matcher: (input) => input.toolName === 'bash',
async handler(input, toolUseId, context) {
console.log(`Executing: ${input.toolInput.command}`);
}
};defaultplanacceptEditsbypassPermissionscanUseToolasync def permission_callback(tool_name, tool_input, context):
if tool_name == "bash" and "git push" in tool_input.get("command", ""):
return False # Deny
return True # AllowdefaultplanacceptEditsbypassPermissionscanUseToolasync def permission_callback(tool_name, tool_input, context):
if tool_name == "bash" and "git push" in tool_input.get("command", ""):
return False # 拒绝执行
return True # 允许执行from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
subagent_definitions={
"researcher": {
"tools": ["read", "grep", "glob"],
"model": "claude-haiku-4",
"description": "Fast research agent"
}
}
)const options = {
subagentDefinitions: {
researcher: {
tools: ['read', 'grep', 'glob'],
model: 'claude-haiku-4',
description: 'Fast research agent'
}
}
};from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
subagent_definitions={
"researcher": {
"tools": ["read", "grep", "glob"],
"model": "claude-haiku-4",
"description": "Fast research agent"
}
}
)const options = {
subagentDefinitions: {
researcher: {
tools: ['read', 'grep', 'glob'],
model: 'claude-haiku-4',
description: 'Fast research agent'
}
}
};undefinedundefinedundefinedundefined@tool(name="check_ui", description="Verify UI matches requirements")
async def check_ui(args):
screenshot = take_screenshot(args["url"])
# Return screenshot to agent for evaluation
return {"content": [{"type": "image", "source": screenshot}]}@tool(name="check_ui", description="Verify UI matches requirements")
async def check_ui(args):
screenshot = take_screenshot(args["url"])
# 返回截图给Agent进行评估
return {"content": [{"type": "image", "source": screenshot}]}judge_result = await secondary_model.evaluate(
criteria="Does output match tone guidelines?",
output=agent_output
)judge_result = await secondary_model.evaluate(
criteria="Does output match tone guidelines?",
output=agent_output
)setting_sources=["project"]["user", "project"]undefinedsetting_sources=["project"]["user", "project"]undefinedundefinedundefinedmcp__{server_name}__{tool_name}mcp__{server_name}__{tool_name}options = ClaudeAgentOptions(add_dirs=["/path/to/data"])options = ClaudeAgentOptions(add_dirs=["/path/to/data"])asynccontinueasync_continue_undefinedasynccontinueasync_continue_undefinedundefinedundefinedreturn {
"content": [{
"type": "text",
"text": "Error: Invalid input. Expected format: ...",
"isError": True
}]
}return {
"content": [{
"type": "text",
"text": "Error: Invalid input. Expected format: ...",
"isError": True
}]
}undefinedundefinedundefinedundefined| Aspect | Python | TypeScript |
|---|---|---|
| Runtime | | Native async/await |
| Min Version | Python 3.10+ | Node.js 18+ |
| Type Safety | Type hints optional | Strict types with Zod |
| Hook Fields | | |
| CLI | Bundled (no install) | Separate install needed |
| Tool Validation | Dict-based schemas | Zod schemas |
| 对比项 | Python | TypeScript |
|---|---|---|
| 运行时 | | 原生async/await |
| 最低版本 | Python 3.10+ | Node.js 18+ |
| 类型安全 | 可选类型提示 | Zod严格类型校验 |
| 钩子字段 | | |
| CLI | 内置(无需额外安装) | 需要单独安装 |
| 工具校验 | 基于字典的Schema | Zod Schema |
undefinedundefined
**TypeScript:**
```typescript
// First run
const result1 = await client.query({ userMessage: 'Create a file' });
// Resume
const result2 = await client.query({
userMessage: 'Now modify it',
sessionId: result1.sessionId
});
**TypeScript示例:**
```typescript
// 首次执行
const result1 = await client.query({ userMessage: 'Create a file' });
// 恢复会话
const result2 = await client.query({
userMessage: 'Now modify it',
sessionId: result1.sessionId
});undefinedundefinedundefinedundefinedoptions = ClaudeAgentOptions(budget={"usd": 5.00})options = ClaudeAgentOptions(budget={"usd": 5.00})import pytest
from unittest.mock import AsyncMock
@pytest.fixture
def mock_tool():
return AsyncMock(return_value={
"content": [{"type": "text", "text": "mocked"}]
})
async def test_agent(mock_tool):
server = create_sdk_mcp_server(name="test", tools=[mock_tool])
# Test with mocked toolimport { jest } from '@jest/globals';
const mockTool = {
name: 'test',
execute: jest.fn().mockResolvedValue({
content: [{ type: 'text', text: 'mocked' }]
})
};import pytest
from unittest.mock import AsyncMock
@pytest.fixture
def mock_tool():
return AsyncMock(return_value={
"content": [{"type": "text", "text": "mocked"}]
})
async def test_agent(mock_tool):
server = create_sdk_mcp_server(name="test", tools=[mock_tool])
# 使用Mock工具进行测试import { jest } from '@jest/globals';
const mockTool = {
name: 'test',
execute: jest.fn().mockResolvedValue({
content: [{ type: 'text', text: 'mocked' }]
})
};import tempfile
import os
async def test_file_operations():
with tempfile.TemporaryDirectory() as tmpdir:
result = await query(
user_message="Create test.txt with content 'hello'",
working_dir=tmpdir,
permission_mode="bypassPermissions"
)
assert os.path.exists(f"{tmpdir}/test.txt")import tempfile
import os
async def test_file_operations():
with tempfile.TemporaryDirectory() as tmpdir:
result = await query(
user_message="Create test.txt with content 'hello'",
working_dir=tmpdir,
permission_mode="bypassPermissions"
)
assert os.path.exists(f"{tmpdir}/test.txt")claude-code-sdkclaude-code-sdkclaude-agent-sdksetting_sourcesClaudeCodeOptionsClaudeAgentOptionssetting_sources=["project"]claude-code-sdkclaude-code-sdkclaude-agent-sdksetting_sourcesClaudeCodeOptionsClaudeAgentOptionssetting_sources=["project"]turn_limitturn_limitadd_dirsadd_dirs