最后审核时间:2026年5月
在终端中练习 CCA-F 考试主题 — Claude Code CLI 命令、Anthropic API 调用、MCP 服务器和多代理模式,每个步骤都对应考试领域。
在本实验结束时,您将已安装 Claude Code,使用 CLAUDE.md 配置了一个项目,构建了一个自定义斜杠命令,连接了一个 MCP 服务器,通过结构化输出练习了 tool_use API,探索了扩展思考,并构建了一个多智能体主管流水线 — 从您的终端覆盖了 CCA-F 考试的所有五个领域。无需云账户或计费;所有操作都在本地运行。
node --version)ANTHROPIC_API_KEY (export ANTHROPIC_API_KEY=sk-ant-...)mkdir cca-f-lab && cd cca-f-lab)对 Anthropic API 的调用会产生基于使用量的费用。步骤 6-8 和 10 使用 claude-sonnet-4-6 模型,其输入 token 费用约为每百万 $3,输出 token 费用约为每百万 $15。本实验的总成本通常低于 $0.15。扩展思考(步骤 7)使用额外的 thinking token,按输出费率计费。
Claude Code 是 CCA-F 考试最直接测试的 CLI 工具——配置、钩子、斜杠命令和权限模式都集中于此。我们首先将其全局安装,以便后续所有步骤都可以调用 claude。
安装后,快速运行 claude --version 可以证明二进制文件位于您的 PATH 中,而 claude --print-system-prompt 则确认 API 密钥有效(它在底层进行了一次轻量级调用)。
# Install Claude Code globally
npm install -g @anthropic-ai/claude-code
# Verify installation
claude --version
# Confirm API connectivity (prints the built-in system prompt)
claude --print-system-prompt | head -20考试会重点测试三层 CLAUDE.md 结构:用户级 (~/.claude/CLAUDE.md)、项目级(仓库根目录)和模块级(子目录)。每个级别都继承自其上级,并且可以覆盖上级的设置。
我们将创建一个项目级文件来设置编码规范,并创建一个用户级文件来设置个人偏好。当 Claude Code 读取项目时,它会合并所有这三层——这正是考试中会问到的行为。
# Create project root CLAUDE.md
cat > CLAUDE.md << 'EOF'
# Project: CCA-F Lab
## Coding conventions
- Use TypeScript for all new files
- Prefer const over let
- Use single quotes for strings
- No semicolons (Prettier default)
## Testing
- Run `npm test` before committing
- All new functions must have at least one test
EOF
# Create user-level CLAUDE.md (applies to ALL your projects)
mkdir -p ~/.claude
cat > ~/.claude/CLAUDE.md << 'EOF'
# User preferences
- Be concise in responses
- Prefer functional programming patterns
- Always explain the "why" before showing code
EOF
# Verify Claude Code sees both files
claude "What instructions do you see in CLAUDE.md?" --print自定义斜杠命令以 Markdown 文件的形式存储在 .claude/commands/ 中。文件名成为命令名称(例如 scaffold.md → /scaffold)。文件内容是提示模板——它可以包含 $ARGUMENTS 用于用户输入。
这是一个高频考点:命令的存放位置、参数的传递方式以及它们与钩子 (hooks) 的区别。
# Create the commands directory
mkdir -p .claude/commands
# Create a scaffold command
cat > .claude/commands/scaffold.md << 'EOF'
Create a new TypeScript module named $ARGUMENTS with:
1. A main source file at src/$ARGUMENTS/index.ts
2. A test file at src/$ARGUMENTS/__tests__/index.test.ts
3. Export the module from the project root index.ts
Follow the coding conventions in CLAUDE.md.
EOF
# Test the command (Claude Code will execute it interactively)
claude /scaffold calculator钩子会响应 Claude Code 事件运行 shell 命令。考试会测试三种钩子类型:PreToolUse(工具运行前)、PostToolUse(工具运行后)和 Notification(状态变更时)。钩子在 .claude/settings.json 中定义。
我们将添加一个 PostToolUse 钩子,它在每次文件编辑后运行 Linter —— 这是一个常见的生产模式,也是考试经常会问到的。
# Initialize a package.json so we have a lint script
npm init -y
npm install --save-dev typescript @typescript-eslint/parser
# Create project-level settings with a post-tool hook
mkdir -p .claude
cat > .claude/settings.json << 'EOF'
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"command": "npx tsc --noEmit 2>&1 | head -5"
}
]
},
"permissions": {
"allow": [
"Read",
"Write",
"Edit"
]
}
}
EOF
# Verify settings are recognized
cat .claude/settings.json模型上下文协议 (MCP) 是考试的核心领域。MCP 服务器通过标准化的 JSON-RPC 协议向 LLM 客户端公开工具、资源和提示。stdio 传输是最简单的——服务器从 stdin 读取并写入 stdout。
我们将构建一个最简 MCP 服务器,它公开一个 get_weather 工具,然后配置 Claude Code 连接到它。这将实践考试测试的完整 MCP 生命周期:工具定义、传输连接、工具调用和结果处理。
# Install the MCP SDK
npm install @modelcontextprotocol/sdk
# Create the MCP server
cat > mcp-weather.mjs << 'EOF'
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({ name: "weather", version: "1.0.0" });
server.tool("get_weather", { city: { type: "string" } }, async ({ city }) => ({
content: [{ type: "text", text: `Weather in ${city}: 72°F, sunny` }],
}));
const transport = new StdioServerTransport();
await server.connect(transport);
EOF
# Register the MCP server in Claude Code settings
cat > .claude/settings.json << 'EOF'
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["mcp-weather.mjs"]
}
}
}
EOF
# Ask Claude Code to use the MCP tool
claude "What is the weather in Tokyo? Use the get_weather tool."考试会详细测试 Messages API 的 tool_use 流程:您在请求中发送 tools,模型以 tool_use 内容块响应,您执行它并返回 tool_result,然后模型生成最终答案。
此步骤使用 curl 直接调用 API —— 这是最符合考试要求的做法,因为考试测试的是原始请求/响应格式,而非 SDK 封装。
# Call the Messages API with a tool definition
curl -s https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"tools": [{
"name": "calculate",
"description": "Evaluate a math expression",
"input_schema": {
"type": "object",
"properties": {
"expression": { "type": "string", "description": "Math expression to evaluate" }
},
"required": ["expression"]
}
}],
"messages": [{
"role": "user",
"content": "What is 15% tip on a $85.50 dinner bill?"
}]
}' | python3 -m json.tool扩展思考允许模型在响应前使用 thinking 块进行逐步推理。考试会测试何时使用它(复杂推理、数学、代码生成)以及如何配置 budget_tokens。
我们将发送一个刻意设计的复杂逻辑谜题,并比较启用和不启用扩展思考时的响应,以便亲身体验质量差异。
# Request WITH extended thinking
curl -s https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 16000,
"thinking": {
"type": "enabled",
"budget_tokens": 10000
},
"messages": [{
"role": "user",
"content": "A farmer has 17 sheep. All but 9 run away. How many does he have left? Explain your reasoning step by step."
}]
}' | python3 -m json.tool
# The response includes a "thinking" block showing the model's
# internal reasoning before the final answer.提示缓存允许您将请求的一部分标记为可缓存。缓存的前缀在后续调用中成本降低 90%,并且没有额外的延迟。考试会测试 cache_control 块的放置位置以及缓存命中时的 HTTP 头。
我们将两次发送相同的长系统提示,并检查响应头以确认第二次调用命中了缓存。
# First call — creates the cache entry
curl -s -D /dev/stderr https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 256,
"system": [{
"type": "text",
"text": "You are a helpful assistant specialized in cloud architecture. You follow AWS Well-Architected Framework principles. You always recommend infrastructure as code. You prefer Terraform over CloudFormation. You prioritize security and cost optimization.",
"cache_control": { "type": "ephemeral" }
}],
"messages": [{ "role": "user", "content": "How should I set up VPC peering?" }]
}' > /dev/null 2>&1
# Second call — should hit the cache (check usage.cache_read_input_tokens)
curl -s https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 256,
"system": [{
"type": "text",
"text": "You are a helpful assistant specialized in cloud architecture. You follow AWS Well-Architected Framework principles. You always recommend infrastructure as code. You prefer Terraform over CloudFormation. You prioritize security and cost optimization.",
"cache_control": { "type": "ephemeral" }
}],
"messages": [{ "role": "user", "content": "What about NAT gateway sizing?" }]
}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"Cache read tokens: {d['usage'].get('cache_read_input_tokens', 0)}\")"考试会测试如何非交互式地运行 Claude Code —— --print 标志会将结果输出到 stdout 而不启动交互式会话,而 --output-format json 则提供结构化输出,便于脚本处理。
这是 CI 流水线中使用的模式:输入提示,获取结果,然后以编程方式解析它。
# Headless mode: prompt in, text out
claude --print "List 3 TypeScript best practices, one per line"
# JSON output for programmatic use
claude --print --output-format json "What is 2+2?"
# Pipe a file for code review (CI pattern)
echo 'const x: any = "hello";' > example.ts
claude --print "Review this TypeScript file for type safety issues: $(cat example.ts)"领域 1(智能体架构,占 27%)是考试中权重最高的。主管模式——一个编排器调度到专业子智能体,每个子智能体都有自己的系统提示和工具集——是考试中最常测试的架构。
我们将构建一个独立的 Node.js 脚本,实现一个主管来协调两个专家:一个研究员负责读取文件并总结,一个作者负责生成输出。主管会分解任务,通过单独的 API 调用委托给每个专家,并汇总结果。从终端运行它,并实时观察任务的委托过程。
# Install the Anthropic SDK
npm install @anthropic-ai/sdk
# Create sample data for the agents to work with
cat > sales-data.csv << 'EOF'
month,revenue,units
Jan,12500,150
Feb,15200,180
Mar,11800,140
Apr,18900,220
May,22100,260
Jun,19500,230
EOF
# Create the multi-agent supervisor script
cat > supervisor.mjs << 'SCRIPT'
import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "fs";
const client = new Anthropic();
async function callAgent(role, systemPrompt, userMessage) {
console.log(`\n--- ${role} agent ---`);
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
system: systemPrompt,
messages: [{ role: "user", content: userMessage }],
});
const text = response.content
.filter((b) => b.type === "text")
.map((b) => b.text)
.join("\n");
console.log(text);
return text;
}
// --- Supervisor: decompose, delegate, aggregate ---
const data = readFileSync("sales-data.csv", "utf-8");
console.log("=== SUPERVISOR: Decomposing task ===");
console.log("Task: Analyze sales data and write a brief executive summary.\n");
console.log("Step 1: Delegate analysis to Researcher agent");
console.log("Step 2: Delegate writing to Writer agent");
console.log("Step 3: Combine results\n");
// Sub-agent 1: Researcher — extracts insights
const analysis = await callAgent(
"Researcher",
"You are a data analyst. Extract key trends, highs, lows, and growth rates. Be precise with numbers. Output bullet points only.",
`Analyze this CSV data:\n\n${data}`
);
// Sub-agent 2: Writer — produces the summary from the analysis
const summary = await callAgent(
"Writer",
"You are a business writer. Write a 3-sentence executive summary from the analysis provided. Use a professional tone. Include specific numbers.",
`Write an executive summary based on these findings:\n\n${analysis}`
);
console.log("\n=== SUPERVISOR: Final aggregated output ===");
console.log(summary);
SCRIPT
# Run the supervisor
node supervisor.mjs本实验完全在本地运行 — 无需清理云资源。
# Remove the lab directory
cd .. && rm -rf cca-f-lab
# Optionally remove the user-level CLAUDE.md we created
rm -f ~/.claude/CLAUDE.md
# Optionally uninstall Claude Code
npm uninstall -g @anthropic-ai/claude-code
本实验侧重于命令行界面 (CLI) 和 API 的实践练习。它不包括: