devHọc Dev

Week 3 - Day 9: CCDV-F exam prep: advanced integration, agent architecture, MCP servers, output handling and guardrails

Week 3 – Day 9

This lesson combines 4 topics: The CCDV-F exam map and the extended Claude API (vision, Bedrock/Vertex AI, batch, SDK), Application design and configuration management, Advanced agent architecture, MCP servers and choosing a tool type, Output handling and layered guardrails.

Learning Objectives

  • Know the format of the Claude Certified Developer – Foundations (CCDV-F) exam and which day of the course covers each domain
  • Send images to Claude through the API, estimate image tokens and know the limits of vision
  • Call Claude through Amazon Bedrock and Google Vertex AI: client, model ID, authentication, feature differences
  • Choose between the Message Batches API and realtime calls based on latency, cost and volume
  • Distinguish zero-shot, single-shot and multi-shot; understand how the SDK wraps the REST API and how SSE streaming differs from websockets
  • Design Claude applications by surface (Claude Code, Desktop, claude.ai, API, SDK), keep sessions clean, design schemas
  • Manage configuration: model pinning, aliases, prompt versioning, settings.json, plugins and plugin dependencies
  • Choose between a workflow and an agent; design a manager/supervisor system with subagents
  • Compare agent deployment models: self-hosted, Anthropic-hosted (Managed Agents), self-hosted sandbox
  • Know where agent frameworks (Strands, LangGraph, PydanticAI) sit relative to the Agent SDK
  • Write an MCP server with tools and resources; choose between the stdio and Streamable HTTP transports
  • Distinguish client-side tools from server-side tools, design an action approval step
  • Choose correctly between a built-in tool, a custom tool, a Skill and an MCP server
  • Check output in layers: stop_reason, parsing, schema, business rules, grounding against sources
  • Build layered guardrails against jailbreaks and prompt injection following the principle of least privilege

Part 1: The exam map and the extended Claude API

1. The CCDV-F exam on one page

According to the official exam guide (version 1.0, effective from 7/2026):

ItemValue
NameClaude Certified Developer – Foundations, code CCDV-F
Questions53, multiple-choice and multiple-response; each question states how many answers to choose
Time120 minutes (about 2.2 minutes per question)
Passing scoreScaled score of 720 on a 100–1,000 scale
ResultPass/fail with a scaled score and the percentage correct per domain
Fee, validity$125, valid for 12 months; renew on time with a free assessment

The eight domains and where to study them in the course:

DomainWeightMain contentWhere to study
1. Agents and Workflows14.7%Workflow or agent, manager/subagent, Agent SDK, Managed Agents, hooks, frameworksDay 6, Part 1; Day 3, Part 2; this lesson, Part 3
2. Applications and Integration33.1%Messages API, tools, streaming, vision, caching, Bedrock/Vertex, batch, SDLC, application design, configurationDay 5; Day 7, Parts 3–4; this lesson, Parts 1–2
3. Claude Code3.1%Rules, Skills, Commands, Agents, memory, headless, CLAUDE.md, settingsDay 2, Day 3
4. Eval, Testing, and Debugging2.6%Classifying errors, choosing a recovery approach, reading traces, separating integration errors from model errorsDay 5, Part 4; Day 6, Part 4
5. Model Selection and Optimization16.8%Tokens, sampling, thinking, effort, zero/multi-shot, SDK wrapping REST, model choice, cost, cacheDay 1; Day 5, Part 3; this lesson, Part 1
6. Prompt and Context Engineering11.0%Context management, prompts, few-shot, system vs user, output handlingDay 1, Part 3; Day 2, Part 4; this lesson, Part 4
7. Security and Safety8.1%Prompt injection, jailbreaks, PII, guardrails, hooks, secretsDay 7; Day 3, Part 3; this lesson, Part 4
8. Tools and MCPs10.6%Tool design, client vs server tools, approval, MCP servers, choosing a tool typeDay 6, Part 2; Day 3, Part 3; this lesson, Part 3

Domain 2 makes up a third of the exam, twice the size of the next domain. Domains 3 and 4 together are under 6%, but their knowledge shows up indirectly in scenario questions in other domains.

How to read a question: the exam is written as scenarios, and several options are "correct in theory". Find the constraint keyword in the question, then eliminate the options that violate it:

Keyword in the questionUsually points to
"cost is the primary concern", "not needed until morning"Message Batches API, cache, a smaller model after measuring
"reusable across several applications", "maintained independently"MCP server
"must never", "guarantee", "deterministic"Hooks, permissions, checks in code, not an instruction in the prompt
"untrusted content", "hidden instructions"Separating data from instructions, least privilege, action approval
"least operational overhead"Managed services, ready-made helpers (Tool Runner, Managed Agents)
"reproducible", "audit"Pinning the model ID, versioning prompts, storing input/output

2. Vision: sending images to Claude

All current models accept images as input (per Vision, as of 11/2026). An image is an image content block in a user message, with three source types: base64, url, or file (a file_id from the Files API, uploaded once and reused many times).

import fs from "node:fs";
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
const screenshot = fs.readFileSync("./bug-checkout.png").toString("base64");

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  messages: [
    {
      role: "user",
      content: [
        // Image before the question: the docs recommend an image-then-text structure
        { type: "image", source: { type: "base64", media_type: "image/png", data: screenshot } },
        { type: "text", text: "This is a screenshot of the broken checkout page. List the elements that render incorrectly and where they are." },
      ],
    },
  ],
});

Numbers and limits to remember (as of 11/2026):

ItemValue
FormatsJPEG, PNG, GIF, WebP; for animated GIFs only the first frame is used
Images per requestUp to 600 on the API (100 for models with a 200K context); above 20 images, a stricter size limit applies to each image
SizeUp to 8000x8000 px; 10 MB per image (base64) on the Claude API, 5 MB on Amazon Bedrock
Maximum resolutionModels from Claude 4.7 onward: long edge 2,576 px, up to 4,784 visual tokens; older models: 1,568 px
Image tokensEach 28x28 px tile is one visual token: ⌈width/28⌉ × ⌈height/28⌉; images larger than the limit are downscaled
Bedrock, Vertex AIAccept only base64 sources

Example: a 1000x1000 px image costs 1,296 visual tokens; a 4K image is downscaled to 2576x1449 and costs 4,784 tokens on current models. Large images cost many tokens, so downscale before sending if the task does not need detail, and measure with count_tokens.

Capability limits, per the docs: Claude does not identify people in images; coordinates and positions are only approximate; counting many small objects may be wrong; it cannot tell whether an image was AI-generated; it is no substitute for a medical diagnosis. For work that must be exactly right, have a person check.

3. Calling Claude through Amazon Bedrock and Google Vertex AI

Enterprises that already have contracts, IAM and billing on AWS or Google Cloud often call Claude through their platform. The official SDK has a separate client for each platform; once initialized, the messages.create / messages.stream surface is the same as the Claude API. The standard client only works with Bedrock's base_url when authenticating with a Bedrock API key (bearer token); for IAM/SigV4 authentication, use the SDK's Bedrock client.

Python:

# Amazon Bedrock: the Mantle client (Bedrock's Messages API-style endpoint)
from anthropic import AnthropicBedrockMantle

bedrock = AnthropicBedrockMantle(aws_region="us-east-1")  # authenticates with AWS credentials, no Anthropic API key needed
resp = bedrock.messages.create(
    model="anthropic.claude-opus-5-5",  # Bedrock: has the anthropic. prefix
    max_tokens=16000,
    messages=[{"role": "user", "content": "Summarize the following return policy: ..."}],
)

# Google Vertex AI: install the extra with `pip install "anthropic[vertex]"`
from anthropic import AnthropicVertex

vertex = AnthropicVertex(project_id="acme-shop-prod", region="global")  # authenticates with Application Default Credentials
resp = vertex.messages.create(
    model="claude-opus-5-5",  # Vertex AI: current models use the plain ID, no prefix
    max_tokens=16000,
    messages=[{"role": "user", "content": "Summarize the following return policy: ..."}],
)

Quick comparison (per Models overview and the SDK's per-platform feature table, as of 11/2026):

Claude APIAmazon BedrockGoogle Cloud (Google managed, Vertex AI)
Opus 5.5 model IDclaude-opus-5-5anthropic.claude-opus-5-5claude-opus-5-5
AuthenticationAPI key (x-api-key), OAuth, Workload Identity FederationAWS credentials (IAM, SigV4), or a Bedrock API keyGoogle Cloud ADC (gcloud auth application-default login), service account
Pricing, quotas, retirement scheduleAnthropicSet by AWSSet by Google Cloud
Messages, streaming, tool use, caching, structured outputs, thinkingYesYesYes
Message Batches API, Files API, Models APIYesNoNo
Web search / web fetch (server tools)Yes / YesNo / NoYes / No
MCP connector, Managed AgentsYes (beta)NoNo

A note on naming: besides the two partner-operated platforms above, there are also Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed), operated by Anthropic, which keep nearly the full Claude API feature set (including Managed Agents). When the exam says "Bedrock" or "Vertex AI", it means the partner-operated platforms in the table.

Design consequence: an architecture that depends on the Batches API, Files API, MCP connector or Managed Agents does not move over as-is to Bedrock or Vertex AI. Check the platform's feature table before settling on an architecture, and use the provider's equivalent mechanism where there is one.

Claude Code also runs through Bedrock (CLAUDE_CODE_USE_BEDROCK=1 with AWS credentials and a region) or Google Cloud, Microsoft Foundry (Day 2, Part 1). When rolling it out to many people, the docs recommend pinning the model version (see Part 2.4).

4. Message Batches API or realtime calls

The Message Batches API (POST /v1/messages/batches) accepts many Messages API requests and processes them asynchronously at 50% of the price for all tokens (stackable with cache discounts). Per the docs (as of 11/2026):

  • Up to 100,000 requests or 256 MB per batch.
  • Most batches finish within 1 hour; the maximum is 24 hours, after which the remaining requests are expired. 24 hours is a deadline, not a timing commitment.
  • Results are kept for 29 days; results come back out of order and must be matched by custom_id.
  • Supports Messages API features (vision, tools, cache...).
import anthropic

client = anthropic.Anthropic()

batch = client.messages.batches.create(
    requests=[
        {
            "custom_id": f"review-{r['id']}",
            "params": {
                "model": "claude-haiku-5-5",
                "max_tokens": 1000,
                "messages": [{"role": "user", "content": f"<review>\n{r['text']}\n</review>\nClassify the sentiment: positive/negative/mixed."}],
            },
        }
        for r in reviews  # list of product reviews read from the DB
    ]
)

# A separate job (cron) checks later: when processing_status == "ended", read the results
status = client.messages.batches.retrieve(batch.id)
if status.processing_status == "ended":
    for item in client.messages.batches.results(batch.id):
        if item.result.type == "succeeded":
            save(item.custom_id, item.result.message.content)
        else:  # errored, canceled, expired
            requeue(item.custom_id, item.result.type)
QuestionRealtime (Messages API)Message Batches API
Is someone waiting for the result?Yes: chat, autocomplete, interactive PR reviewNo: nightly reports, backlog classification, eval runs, backfill
Acceptable latencySecondsMinutes up to 24 hours
CostStandard price50%
Rate limitsSubject to RPM/ITPM/OTPMSeparate batch quota, does not consume realtime quota
Error handlingPer request, retry immediatelyRead result.type for each request, collect the failed requests and rerun them

Common traps: "send 10,000 requests in parallel to go faster" does not lower the per-token price and easily hits 429; "cut max_tokens" is not a cost lever but a way to break the output (Day 5, Part 1).

5. Zero-shot, single-shot, multi-shot

The terms the exam uses for the number of examples in a prompt:

TermThe prompt hasGood whenRisk
Zero-shotInstructions, no examplesCommon tasks, instructions are clear enoughFormat and tone drift from expectations
Single-shot (one-shot)One input/output exampleYou need to lock the formatThe model copies the details of the single example too closely
Multi-shot (few-shot)3–5 diverse examplesClassification with fuzzy boundaries, complex formats, a distinctive toneCosts tokens; skewed examples pull the output with them

Good practice (Day 1, Part 3): wrap examples in <example> tags, choose diverse examples including edge cases, put stable examples in the cached part, and measure with an eval whether the examples actually help. With current models no longer supporting prefill, examples and structured outputs are the two main ways to lock the format.

6. The SDK wraps REST, streaming and websockets

The Claude API is a REST API over HTTPS: POST /v1/messages with the x-api-key and anthropic-version headers and a JSON body. The official SDKs (Python, TypeScript, Java, Go, Ruby, C#, PHP) wrap REST and add:

The SDK handlesIf you call HTTP yourself, you must
Reading credentials from the environment, version headersAttach headers and manage keys yourself
Retrying 408/409/429/5xx with backoff (2 times by default), timeoutsWrite your own retries, and easily retry 400 errors by mistake
Typed error classes (RateLimitError, BadRequestError...)Match HTTP codes and error strings
Types for requests/responses, the parse helper, stream().finalMessage(), Tool RunnerDefine types yourself, assemble the event stream yourself

The course's rule: if the project has an official SDK, use the SDK; call raw HTTP only when the language has no SDK or the environment only has a shell.

Messages API streaming is Server-Sent Events (SSE) over HTTP, one-way from server to client: message_start, content_block_delta, message_stop... You do not need a websocket to receive a stream from Claude. Websockets (a two-way, long-lived connection) usually sit on the leg between your backend and the browser when the application needs to push events both ways (the user interrupts, agent status updates). A typical architecture:

Browser◀──websocketorSSE──▶Yourbackend──HTTPS+SSE──▶ClaudeAPI(UI)(two-way,yourchoice)(holdsAPIkey,(one-waystream)validates,logs)

The API key lives only in the backend; the browser never calls the Claude API directly with your key.


Part 2: Application design and configuration management

1. Claude receives instructions differently on each surface

It is the same model, but instructions come from different sources depending on the surface. Understanding where instructions come from helps you put rules in the right place:

SurfaceYour instructions come fromWho controls the loop and toolsDesign notes
claude.ai, Claude Desktop (chat)Messages, Projects, settings, enabled connectors/pluginsAnthropic's applicationDoes not touch your repo unless there is a connector; good for Q&A and documents
Claude Code (CLI, IDE, Desktop, web)CLAUDE.md, rules, skills, settings, your promptsClaude Code; you constrain it with permissions and hooksMandatory rules go in permissions/hooks, not only in CLAUDE.md
Claude APIsystem, messages, tools definitions sent by your codeYour codeNo CLAUDE.md or skill is loaded automatically; everything must be in the request
Agent SDKsystemPrompt, options, and (depending on the settings source configuration) CLAUDE.md and skills from .claude/A library that runs the Claude Code engine on your infrastructureControl the configuration sources when running on an untrusted repo (Day 6, Part 1)

Two consequences that often come up in the exam:

  • "CLAUDE.md has no effect on an application that calls the API": CLAUDE.md is a Claude Code mechanism (and the Agent SDK's when it loads project sources). An application that calls the Messages API must put its own rules in system.
  • Content boundaries: your instructions go in system; user data and external content go in messages, wrapped in XML tags or passed through tool_result (Part 4). Do not insert user content into system to "make the model pay more attention".

2. Session hygiene: keeping sessions clean

A "session" is a series of turns that share one context. A dirty session (many tasks mixed together, old wrong directions, huge tool output) lowers quality and raises cost on every later turn.

WherePractice
Claude CodeOne session per task; /clear when switching tasks; /compact <focus> for long tasks; /rewind when going the wrong way; hand read-heavy work to a subagent (Day 2, Part 4)
API applicationsA separate history for each conversation per user; never mix two people's histories; cap history length, use compaction or context editing (beta) for long conversations
AgentsTrim tool output (pagination, summaries), clear old tool results that are no longer needed, isolate read-heavy work in subagents
SecurityUser A's session must never contain user B's data; remove sensitive data from logs according to policy

The history is append-only (Day 5, Part 1): to add instructions midway, append a new message rather than editing an old turn. With current models, editing an old turn can invalidate thinking blocks and break the cache.

3. Schema design

Schemas appear in three places: a tool's input_schema, structured outputs (output_config.format), and the data you store. General principles:

PrincipleExampleWhy
enum for finite value sets"status": {"enum": ["pending", "paid", "shipped"]}No more spelling variants
required + additionalProperties: falseMandatory with strict: trueNo missing fields, no extra fields
Meaningful field names with a descriptiontotal_vnd instead of tThe model fills it correctly; people reading logs understand it too
A valid way out"category": {"enum": [..., "other"]}, a needs_human_review fieldForcing a wrong choice is worse than allowing "not sure"
Flat and just big enoughAvoid 5 levels of nestingEasy to validate, fewer errors
Version the schemaschema_version: 2 in stored dataChange the schema without breaking old consumers

Structured outputs guarantee syntax and schema, not correct content (Day 5, Part 2). Checking content is the job of Part 4.

4. Model pinning and aliases

Two worlds to tell apart:

Claude API: per Models overview (as of 11/2026), every model ID is a fixed snapshot, including the IDs without a date suffix used since the 4.6 generation (claude-opus-5-5). For models before the 4.6 generation, an alias like claude-sonnet-4-5 is a pointer to the dated ID claude-sonnet-4-5-20250929. For reproducibility, record the specific model ID in configuration and logs.

Claude Code: the aliases opus, sonnet, haiku change over time, pointing to the version recommended for the provider (per Model configuration). On Bedrock and Google Cloud, an alias may point to an older version than on the Claude API. To make the whole team use the same model:

{
  "model": "opus",
  "env": {
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-5-5"
  }
}

Or put the full model ID directly in model. Organizations restrict which models can be chosen with availableModels in managed settings.

Why pinning matters: new models have breaking changes (Day 1, Part 2: prefill removed, sampling removed, forced tool_choice returns 400...) and different behavior. Changing the model is a change that requires rerunning the eval like any code change, not an "automatic update".

5. Prompt versioning

Prompts are code: changing one sentence can change the behavior of a whole feature.

PracticeDetails
Prompts live in the repoA separate file (prompts/classify_ticket.v3.md), reviewed through PRs like code
Every prompt has a versionLog prompt_version along with the model ID, effort and request ID for each request (Day 6, Part 4)
Prompt changes go through evalCompare the old and new versions on a fixed eval set before shipping to production
Rollback is possibleConfiguration selects the prompt version; going back to the previous version needs no code deploy
Do not mix model changes and prompt changesChange one variable at a time so you know where an improvement or regression comes from

With Managed Agents, an agent is a versioned configuration: each update creates a new version, and a session is bound to the version current when it was created, so rollback and A/B tests are possible.

6. settings.json, plugins and plugin dependencies

Recap of Day 2, Part 3: Claude Code reads settings in priority order managed → command line → .claude/settings.local.json → .claude/settings.json → ~/.claude/settings.json; permission lists are merged, and deny always wins.

A plugin (per Plugins, as of 11/2026) is a directory that packages several components that are installed and loaded as one unit: skills, agents (subagents), hooks, MCP servers, LSP servers...

deploy-tools/├──.claude-plugin/│└──plugin.json#manifest:name(required),version,dependencies...├──skills/deploy/SKILL.md#runsas/deploy-tools:deploy├──agents/reviewer.md#subagentdeploy-tools:reviewer├──hooks/hooks.json└──.mcp.json#MCPserversstartedwhilethepluginisenabled
{
  "name": "deploy-tools",
  "version": "1.2.0",
  "description": "Deploy commands, a review agent and check hooks",
  "dependencies": ["secrets-vault"]
}

Points to remember:

  • Every component is namespaced by the plugin name: the deploy skill in the deploy-tools plugin runs as /deploy-tools:deploy, avoiding name clashes between plugins.
  • version in the manifest keeps users on that version until the author changes it; this is the plugin's pinning mechanism.
  • dependencies lists other plugins that must be enabled for this plugin to work, as "name", "name@marketplace" or an object with a version. Depended-on plugins are enabled along with it.
  • Plugins are installed from a marketplace (a catalog with .claude-plugin/marketplace.json), for example commit-commands@claude-plugins-official. Install scopes: user, project (through .claude/settings.json committed to the repo), local.
  • An enabled plugin always adds the names and descriptions of its skills and agents to the context on every turn, and its MCP servers run with every session. Enable what you need, disable what you do not use.
  • Plugins run code with your permissions. Organizations control allowed marketplaces and required plugins with managed settings.
  • Validate the manifest with claude plugin validate ./deploy-tools (add --strict in CI).

When you need a plugin: when you want to package several skills, subagents, hooks and MCP servers into one versioned unit to share across many repos or many teams. A skill used only in one repo is fine in .claude/skills/.


Part 3: Advanced agent architecture, MCP servers and choosing a tool type

1. Workflow or agent: deciding by criteria

Day 6, Part 1 covered the three levels: single call, workflow, agent, along with four questions (complexity, value, feasibility, cost of mistakes). Anthropic's article Building effective agents draws a clear line:

  • Workflow: LLMs and tools are orchestrated through predefined code paths.
  • Agent: the LLM dynamically directs its own process and tool usage.

Common workflow patterns:

PatternHow it worksExample
Prompt chainingA chain of steps, each step's output is the next step's input, with gates between stepsGenerate an outline → check → write the article
RoutingClassify the input, then send it to a specialized flowBilling tickets go to one prompt, technical tickets to another; easy questions go to Haiku 5.5
ParallelizationRun independent parts in parallel (sectioning) or run several times to vote (voting)A security review and a performance review run in parallel
Orchestrator-workersOne LLM splits work dynamically, hands it to workers, combines the resultsFixing a feature that touches an unknown number of files
Evaluator-optimizerOne LLM generates, another grades against criteria, loop until it passesTranslating technical documents with a terminology rubric

Choose a workflow when the steps are known in advance and you need predictability, easy testing and stable cost. Choose an agent when the number and order of steps are not known in advance, the work needs exploration, and there is a way to detect and recover from errors.

2. Manager/supervisor systems and subagents

When an agent has to do a lot of context-heavy work (read 40 files, look up 10 sources), split it into a manager (orchestrator, supervisor) and subagents (workers):

┌──────────────────────────────┐│Manager(orchestrator)││plans,delegates,merges││context:task+summaries│└──────┬────────┬────────┬─────┘│││eachgetsanarrowtask▼▼▼┌──────────┐┌──────────┐┌──────────┐│WorkerA││WorkerB││WorkerC││own││own││own││context,││context,││context,││tools││tools││tools│└────┬─────┘└────┬─────┘└────┬─────┘└───────────┴───────────┘shortstructuredresults

Subagents improve execution because of:

  • Context isolation: the heavy reading stays in the worker's context, and the manager receives only summaries. This is also how you fight context bloat and context drift.
  • Least privilege by role: a worker that reads untrusted content has only read tools; the manager has write permissions but does not read raw content (Day 7, Part 2).
  • Choosing the model per task: reading/summarizing workers use Haiku 5.5 or Sonnet 5.5, the manager uses Opus 5.5.
  • Parallelism: independent parts run at the same time.

The cost: more tokens overall, harder debugging, and summaries can lose detail. Good design:

  • Hand work to a worker like assigning a ticket: goal, scope, result format, stopping condition.
  • Workers return structured results (JSON with a schema) instead of long prose.
  • The manager does not blindly trust worker results: it checks required fields and evidence (file:line, URL).
  • Do not split tightly dependent work into parallel tasks (Day 3, Part 2).

In Claude Code, subagents are declared in .claude/agents/ (Day 3, Part 2). The Agent SDK has similar subagents. Managed Agents has a multiagent configuration with subagents and workflows that run several agents.

3. Agent deployment models: who hosts the loop, who hosts the tool runtime

Two independent questions separate the ways to build an agent (extending the table in Day 6, Part 1):

ApproachThe agent loop runs onTools execute onYou operate
Hand-written loop, Tool RunnerYour infrastructureYour infrastructureEverything
Agent SDKYour infrastructure (the Claude Code engine)Your infrastructureEverything, but with built-in tools, hooks, subagents
Managed Agents, cloud environmentAnthropicAn Anthropic-hosted container, one container per sessionAgent configuration, sending messages, returning custom tool results
Managed Agents, self-hosted sandboxAnthropicYour infrastructure (a worker connects outbound to receive work)The worker and the tool runtime

Per the docs (as of 11/2026, beta):

  • Managed Agents: create an Agent once (model, system, tools, MCP servers, skills; versioned), and each run creates a Session that references the agent. The session streams events back to you.
  • A self-hosted sandbox keeps the file and network data of the tool runtime inside your infrastructure; connections are outbound only (the worker long-polls Anthropic's queue), and Anthropic does not call into your network. Tool results still go back to the control plane for the model to read.
  • Permission policies for server-side tools: always_allow, always_ask (the session pauses waiting for your confirmation), auto (the server evaluates each call: run, deny, or pause for approval). The default for MCP toolsets is always_ask.
  • Managed Agents is not available on Amazon Bedrock or Vertex AI; agents on those platforms are built with the Claude API + tool use or the Agent SDK.

Choose by requirement:

RequirementSuitable direction
Data must not leave the VPC, tools must run on the internal networkSelf-hosted (Agent SDK, hand-written loop) or a self-hosted sandbox
Least operations, long-running agents, a dedicated container per sessionManaged Agents cloud environment
Only allowed to use Claude through BedrockAgent SDK or a hand-written loop on Bedrock
The agent uses only a few of your business tools and needs per-turn controlTool Runner or a hand-written loop

Hooks for deterministic actions: in every model, things that must happen 100% of the time (blocking dangerous commands, formatting code, writing audit logs) go in a hook or in harness code, not in the prompt (Day 3, Part 3). The Agent SDK has hooks like Claude Code; in a hand-written loop, it is simply your code before and after running a tool.

4. Agent patterns and frameworks

Patterns that appear in every agent, whatever it is built with:

PatternMeaningWhere in the course
Tool-use loopCall the model → run tools → return results → repeat until done; with a turn limit and a budgetDay 5, Part 2; Day 6, Part 1
SubagentIsolate context and permissions per subtaskDay 3, Part 2; section 2 above
MemoryKeep knowledge across sessions: files (CLAUDE.md, auto memory), memory tool, memory storeDay 2, Part 2
Context window managementTrim tool output, compaction, context editing, subagentsDay 2, Part 4; Part 2.2 above

Agent frameworks are abstraction layers that help build agents and multi-step workflows; an overview for the exam:

FrameworkPositioningWhen to consider
Strands AgentsAn open-source SDK (started by AWS) with a "model-driven" approach: declare the model, prompt and tools, and let the model drive the loopTeams already on the AWS ecosystem who want a lean agent running with Claude on Bedrock or the Claude API
LangGraphModels agents/workflows as a state graph (nodes, edges, state), with checkpointing and pausing for human approvalMany-branch flows that need explicit step-by-step control, long-running and stateful
PydanticAIA Python framework that prioritizes type safety: agent output is validated with Pydantic models, tools are typedPython applications that need strictly structured output, teams familiar with Pydantic
Claude Agent SDKThe Claude Code engine as a library: built-in tools, hooks, subagents, permissionsAgents that work with files and commands; when you want Claude Code-like behavior

Frameworks do not replace the principles: good tool design, least privilege, evals, transcript logging. The right question is not "which framework is the most powerful" but "which abstraction layer is just enough for the requirement"; many tasks only need a loop of a few dozen lines or Tool Runner. The API details of each framework change quickly, so check that project's docs when you use it.

5. Client-side tools and server-side tools

TypeWho defines itWho executes itExampleWhat you receive
Custom tool (user-defined)You (name, description, input_schema)Your codeget_order_status, refund_orderstop_reason: "tool_use"; you run it, then send a tool_result
Anthropic-defined client-side toolAnthropic (ready-made schema, declared with type)Your harnessBash, text editor, memory, computer use (self-hosted)Same as a custom tool; Anthropic provides a reference implementation
Server-side toolAnthropicAnthropic's infrastructureWeb search, web fetch, code execution, tool searchThe result is right in the response; a long server loop may return pause_turn
MCP connector (beta)Your remote MCP server or a third party'sThe MCP server; Anthropic connects server-sideAn issue tracker server exposed at a public URLTool results in the response; needs both mcp_servers and mcp_toolset

Design consequences:

  • A tool that needs access to internal systems (a database behind a firewall, an internal API) must be a client-side tool or an MCP server you host; server-side tools cannot reach your internal network.
  • Server-side tools have no approval step in your code between when the model calls them and when they run; limit them with configuration (for example allowed_domains, max_uses) and enable them only when needed.
  • With client-side tools, all permission checks, input validation and business limits live in your code (Day 6, Part 2).

6. Action approval patterns

LevelMechanismUsed for
AutomaticAllow-list, always_allowRead-only tools with a narrow scope
Rule-based approval in codeCode checks before running: amount under a threshold, order belongs to the authenticated userRepeated, low-risk write actions
Human approval (human-in-the-loop)The loop pauses, shows the tool + parameters, waits for consent; Claude Code ask; Managed Agents always_askLarge refunds, deleting data, sending external email, deploying
ForbiddenDeny rule, PreToolUse hook exit 2, the tool is not grantedActions that must never happen

Example approval gate in a hand-written loop (TypeScript, condensed from the loop in Day 5, Part 2):

const NEEDS_APPROVAL = new Set(["refund_order", "send_email"]);

for (const block of response.content) {
  if (block.type !== "tool_use") continue;
  if (NEEDS_APPROVAL.has(block.name)) {
    const ok = await askHumanApproval(block.name, block.input); // UI or approval queue
    if (!ok) {
      results.push({
        type: "tool_result",
        tool_use_id: block.id,
        content: "The operator rejected this action. Do not retry; tell the customer the request needs manual handling.",
        is_error: true,
      });
      continue;
    }
  }
  results.push(await runTool(block)); // runTool checks permissions and business limits itself
}

A rejection still returns a tool_result with guidance so the model does not call the same action again. With Tool Runner, deterministic rules (amount thresholds, ownership) go inside the tool function itself; when you need human approval before running, the Tool Runner docs recommend a hand-written loop like the one above.

7. Writing an MCP server

An MCP server provides three kinds of capabilities (per modelcontextprotocol.io):

PrimitiveWhat it isExample for acme-shop
ToolsFunctions the model can call (usually with user approval)check_stock(sku), reserve_stock(sku, qty)
ResourcesFile-like data the client can readinventory://warehouses, the list of warehouses
PromptsPre-built templates that help the user do a task"Low-stock report by warehouse"

Roles: the host is the AI application (Claude Code, Claude Desktop, your application); a client is the component inside the host that holds the connection to one server; a server is the program that provides tools/resources/prompts. One host can connect to many servers.

A minimal Python server with the official SDK (as of 11/2026, the SDK uses the MCPServer class; older projects may still use the name FastMCP):

# inventory_server.py
import json
import sys

from mcp.server import MCPServer

mcp = MCPServer("acme-inventory")


@mcp.tool()
async def check_stock(sku: str) -> str:
    """Look up the stock of one SKU across all warehouses.

    Args:
        sku: SKU code in the form ACM-12345
    """
    rows = await inventory_api.get_stock(sku)  # calls the internal REST API with read-only credentials
    if not rows:
        return f"SKU {sku} not found. SKUs have the form ACM- followed by 5 digits."
    return json.dumps({"sku": sku, "warehouses": rows}, ensure_ascii=False)


@mcp.resource("inventory://warehouses")
def list_warehouses() -> str:
    """List of warehouses and the regions they serve."""
    return json.dumps(WAREHOUSES, ensure_ascii=False)


if __name__ == "__main__":
    print("acme-inventory MCP server starting", file=sys.stderr)  # log to stderr, never stdout
    mcp.run(transport="stdio")

The SDK uses type hints and docstrings to generate the tool definition, so the docstring is the tool description: write it following the principles in Day 6, Part 2 (what it does, when to use it, what it returns, errors with guidance).

The TypeScript version uses McpServer and registerTool with a Zod schema:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";

function createServer() {
  const server = new McpServer({ name: "acme-inventory", version: "1.0.0" });
  server.registerTool(
    "check_stock",
    {
      description: "Look up the stock of one SKU across all warehouses. Use before promising a delivery date.",
      inputSchema: z.object({ sku: z.string().regex(/^ACM-\d{5}$/).describe("SKU code in the form ACM-12345") }),
    },
    async ({ sku }) => ({ content: [{ type: "text", text: JSON.stringify(await getStock(sku)) }] }),
  );
  return server;
}

serveStdio(createServer); // log with console.error, never console.log

Transports (per the MCP spec, as of 11/2026):

TransportHow it runsGood whenNotes
stdioThe client launches the server as a child process; newline-delimited JSON-RPC over stdin/stdoutLocal, single-user servers: file-reading tools, internal CLIsThe server must not write anything to stdout other than MCP messages (log to stderr); print() or console.log breaks the protocol
Streamable HTTPThe server is an independent process with one HTTP endpoint (for example https://mcp.acme.dev/mcp), returning JSON or an SSE streamServers shared by many clients and applications, deployed as a serviceValidate the Origin header, bind to 127.0.0.1 when running locally, require authentication; replaces the old HTTP+SSE transport
Custom (for example a Unix socket, TCP)You define itSpecial needsThe spec recommends reusing stdio's framing

Integrating with Claude applications:

# Claude Code: local stdio server, project scope so the whole team uses it (written to .mcp.json)
claude mcp add --transport stdio --scope project acme-inventory -- uv run inventory_server.py

# Claude Code: an already-deployed HTTP server
claude mcp add --transport http acme-inventory https://mcp.acme.dev/mcp
  • Agent SDK: declare MCP servers in the options.
  • Messages API: the MCP connector (beta) for remote servers by URL.
  • Managed Agents: declare MCP servers on the agent, with credentials stored in a vault.

Deploying an MCP server as a service: the server's credentials have only enough permissions for the tools it provides; authenticate clients; log every tool call; version the server and keep tool names backward compatible, because renaming a tool breaks the prompts and skills that rely on it.

8. Choosing a built-in tool, a custom tool, a Skill or MCP

This is the "Agentic Customization" topic of Domain 8. Decision table:

OptionWhat it isChoose whenDo not choose when
Built-in toolTools the platform already has: Read/Edit/Bash/Grep in Claude Code and the Agent SDK; web search, code execution on the APIA general need already met by a tool (reading files, running commands, searching the web)You need access to your own systems; built-in tools cannot reach internal APIs
Custom toolA function you define inside the application itself (tools in the Messages API)Logic tied to one application that needs tight control in the app's codeMany applications need the same capability and would have to copy the code
SkillA package of instructions + supporting files (SKILL.md, scripts, templates); only the name and description sit in context, the content loads when neededTeaching Claude how to do a process: release conventions, how to write migrations, creating an .xlsx file from a templateYou need a realtime connection to external data or systems
MCP serverA standardized service that provides tools/resources/prompts to any MCP-capable hostA capability reused across many applications, maintained independently, with its own lifecycle (inventory, issue tracker, database)Only one application uses it and the logic is small: an extra process and an extra operations layer are overkill

Quick questions for choosing:

  1. Is there already a built-in tool that can do it? If so, use it.
  2. Is what you need to add knowledge/a process or access to a system? Knowledge/process → Skill (optionally with scripts). System access → tool.
  3. Is the tool for one application or many? One → custom tool. Many, maintained independently → MCP server.
  4. Do you need to package several of the above for versioned distribution? → Plugin (Part 2.6).

Combining them is normal: a plugin containing an "inventory count process" skill that calls tools from the acme-inventory MCP server.


Part 4: Output handling and layered guardrails

1. Be skeptical of confident output

Model output sounding certain does not mean it is correct (Day 1, Part 1). The confidence level in the text is not a probability of being right; a "95% confidence" figure that the model reports about itself is not calibrated either. The right approach:

  • Demand verifiable evidence: cite file:line, quote the exact passage from the document (use citations when passing documents through the API), source URLs.
  • Verify with tools, not by asking the model again: run tests, type check, query the database, compare with the original source. Asking "are you sure?" just produces another confident paragraph.
  • Allow "I don't know" in the prompt and schema (a needs_human_review field, an unknown value).
  • Measure correctness with evals on labeled data (Day 6, Part 3), not on gut feeling.

2. Checking a response in layers

response│▼1.stop_reasonok?end_turn/tool_useexpected;max_tokens,refusal,pause_turnhandled│▼2.parsesafelystructuredoutputsorstricttoolinput;JSON.parseintry/catch│▼3.schemavalidateZod/Pydanticatyourboundary,evenwithstructuredoutputs│▼4.businessrulesidsexist,totalsaddup,enumallowedforthisuser,datessane│▼5.groundingcheckquotedtextreallyinsource,citedorderreallybelongstouser│▼accept──or──▶limitedretrywitherrorfeedback──or──▶fallback/humanreview

A TypeScript example of steps 1–4 when extracting refund information from a customer email:

import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";

const RefundRequest = z.object({
  order_id: z.string().regex(/^A\d{4}$/),
  amount_vnd: z.number().int().positive(),
  reason: z.enum(["damaged", "late", "wrong_item", "other"]),
  needs_human_review: z.boolean(),
});

function acceptRefund(response: Anthropic.Message, userId: string) {
  if (response.stop_reason === "refusal") return { status: "refused" as const };
  if (response.stop_reason !== "end_turn") return { status: "retry" as const, why: response.stop_reason };

  const text = response.content.find((b) => b.type === "text")?.text;
  let raw: unknown;
  try {
    raw = JSON.parse(text ?? "");
  } catch {
    return { status: "retry" as const, why: "invalid_json" };
  }

  const parsed = RefundRequest.safeParse(raw);
  if (!parsed.success) return { status: "retry" as const, why: parsed.error.message };

  const order = orders.get(parsed.data.order_id);
  // Business rules in code: the order must belong to the authenticated user, the amount must not exceed the order value
  if (!order || order.userId !== userId) return { status: "reject" as const, why: "order_not_owned" };
  if (parsed.data.amount_vnd > order.totalVnd) return { status: "human_review" as const, why: "amount_exceeds_order" };

  return { status: "ok" as const, data: parsed.data };
}

Defensive parsing principles:

  • Do not extract JSON from prose with a regex; use structured outputs or a tool with strict: true.
  • Do not read content[0]; filter blocks by type (Day 5, Part 1).
  • Parse tool_use.input as an object; do not string-match on serialized JSON.
  • Never eval or directly run code, SQL or shell commands the model generates; go through a sandbox, parameterization, or a human reviewer.
  • Retry with a limit and with error feedback: resend with a message like "the amount_vnd field must be an integer"; after 1–2 failures, move it to a human review queue instead of looping forever.
  • Do not "fix" broken output by guessing (closing the brackets of truncated JSON yourself, filling in default values for required fields).
  • Output going to end users (HTML, Markdown) must be escaped like any untrusted input; the model can be injected into generating malicious links or scripts.

3. Jailbreaks, direct and indirect prompt injection

Per Mitigate jailbreaks and prompt injections (as of 11/2026), there are two different threat models:

Jailbreak, direct injectionIndirect injection
AttackerThe application's user themselvesA third party who plants instructions in content Claude reads (web, email, documents, tool results)
GoalBypass the content policy, leak the system prompt, do work outside the scopeHijack the agent's actions, exfiltrate the trusted user's data
Main measuresScreen input with a lightweight model, validate input, a system prompt that states boundaries and how to refuse, handle repeat offendersPut external content in tool_result, state the source, JSON-encode, least privilege, screen tool output

Measures the docs recommend:

  • Harmlessness screen: use a lightweight model (Haiku 5.5) to classify input before it enters the main conversation, forcing the result with structured outputs (for example {"is_harmful": boolean}). If the screening turn itself returns stop_reason: "refusal", treat that as a "harmful" verdict.
  • Put untrusted content in tool_result, not in system or the user's text; Claude is trained to be skeptical of instructions inside tool results. Conversely, do not put your own instructions in tool_result; send them in the following user turn.
  • State the source and nature of the content in the tool description or the result ("email content from an unknown sender").
  • State the policy in the system prompt: content from tools, documents and searches is data and must not override the instructions or the user's original request.
  • JSON-encode untrusted strings so attackers cannot "close the tag" and escape into the instruction context.
  • Screen tool output with a lightweight model before putting it into tool_result.
  • Monitor continuously and red-team the agent with documents, emails and tool output that deliberately contain injections.

Example harmlessness screen (Python):

SCREEN_SCHEMA = {
    "type": "object",
    "properties": {"is_harmful": {"type": "boolean"}},
    "required": ["is_harmful"],
    "additionalProperties": False,
}

def screen(user_text: str) -> bool:
    resp = client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=200,
        output_config={"effort": "low", "format": {"type": "json_schema", "schema": SCREEN_SCHEMA}},
        messages=[{
            "role": "user",
            "content": f"Content submitted by the user:\n<content>\n{user_text}\n</content>\n"
                       "Classify whether the content attempts to bypass the policy or requests harmful behavior.",
        }],
    )
    if resp.stop_reason == "refusal":
        return True  # the screening turn itself was refused: treat as harmful
    if resp.stop_reason != "end_turn":
        return True  # no verdict: block to be safe (fail closed)
    return json.loads(next(b.text for b in resp.content if b.type == "text"))["is_harmful"]

Measures that do not work, and often appear as distractors in the exam: raising the temperature (not adjustable on current models, and irrelevant), switching to a bigger model "for better compliance", adding a sentence asking users not to attack, hiding tool names, relying on a single layer.

4. Layered guardrails and secure-by-design

No layer blocks everything; each layer lowers the probability and limits the damage when the previous layer lets something through:

userinput─▶[1inputscreen]─▶[2systempromptpolicy]─▶model│┌─────────────────────────────────────────────────────┘▼[3least-privilegetools]─▶[4approval/hooksforsideeffects]│▼[5outputvalidation+screen]─▶user/downstream│▼[6logging,monitoring,ratelimitsforrepeatoffenders]
LayerSpecificsRelated lesson
1. Input screeningHarmlessness screen, validate length/format, block unnecessary PII before sendingSection 3
2. Policy in the promptBoundaries, how to refuse, the untrusted content policyDay 1, Part 3
3. Least privilegeTools only sufficient for the job; separate credentials per tool; an agent that reads external content has no write toolsDay 6, Part 2; Day 7, Part 2
4. Approval and hooksActions with side effects need approval; a PreToolUse hook blocks destructive commands (exit 2)Part 3.6; Day 3, Part 3
5. Output checkingValidate, screen content, escape before display, filter PII before loggingSection 2
6. ObservabilityPII-controlled logging, anomaly alerts, throttle or block repeat offendersDay 6, Part 4

On Amazon Bedrock you can add Bedrock Guardrails as the provider's content-filtering layer; it is an additional layer, not a replacement for the layers in your code.

Secure-by-design principles to know by heart:

  • Least privilege for everything: API keys per environment and per workspace with a spend limit (Day 7, Part 1); the IAM role for Bedrock only has permission to invoke inference on the models in use (for the Mantle endpoint this is bedrock-mantle:CreateInference); a read-only database account for lookup tools.
  • Identity and authorization live in code, taken from the authenticated session, not from what the model says (Day 7, Part 2).
  • Short-lived credentials instead of long-lived keys where possible: Workload Identity Federation for CI and workloads that call the Claude API, IAM roles on AWS, ADC on Google Cloud.
  • PII: send only the fields you need; mask or pseudonymize before putting data into prompts, evals and logs; follow the organization's data retention policy.
  • Access monitoring: log who called what, with which key; alert on unusual cost or traffic.

Review Questions

  1. How many questions does the CCDV-F exam have, how many minutes, and what is the passing score? Which domain has the largest weight?

    Show answer

    53 multiple-choice and multiple-response questions (each states how many answers to choose), 120 minutes, passing with a scaled score of 720 or more on a 100–1,000 scale. Domain 2 (Applications and Integration) makes up 33.1%, twice the next domain (Domain 5, 16.8%).

  2. About how many visual tokens does a 1920x1080 screenshot sent to Opus 5.5 cost? What do you do if a pipeline processes tens of thousands of images and does not need fine detail?

    Show answer

    The image does not exceed the current models' 2,576 px limit, so it is not downscaled: ⌈1920/28⌉ × ⌈1080/28⌉ = 69 × 39 = 2,691 visual tokens. If detail is not needed, downscale the images before sending to cut tokens and latency, measuring with count_tokens on sample images; if the work is not urgent, run it through the Message Batches API for a 50% discount.

  3. A team is moving an application from the Claude API to Amazon Bedrock. The application uses the Message Batches API for nightly reports and web search. What should they watch out for?

    Show answer

    Use the SDK's Bedrock client (Mantle), model IDs with the anthropic. prefix, authentication with AWS credentials/IAM instead of an Anthropic API key, and pricing and quotas set by AWS. The Message Batches API and web search are not available on Bedrock per the SDK's feature table, so they must redesign: use the provider's batch mechanism if there is one, and replace web search with a self-hosted tool. Check the feature table before settling on an architecture.

  4. When do you choose the Message Batches API over realtime calls? How must batch results be read?

    Show answer

    When nobody is waiting for the result and a latency of up to 24 hours is acceptable: nightly reports, backlog classification, evals, backfill. Batches cut all tokens by 50% and have a separate quota. Results come back out of order, so match them by custom_id; check result.type (succeeded, errored, canceled, expired) for each request and rerun the failed requests.

  5. Distinguish zero-shot, single-shot and multi-shot. When is multi-shot worth the extra cost?

    Show answer

    Zero-shot: instructions only. Single-shot: one example. Multi-shot: several examples (usually 3–5). Multi-shot is worth it when the format is complex, classification boundaries are fuzzy, or you need a distinctive tone that a description cannot capture; the examples must be diverse so the model does not copy one sample too closely, placed in the cached part, and measured with an eval to see whether they really help.

  6. A colleague wants to use a websocket to "receive the stream from the Claude API faster". How do you explain it?

    Show answer

    Messages API streaming is SSE over HTTP, one-way from the server; the SDK already has helpers for reading the stream. Websockets are not used to call the Claude API, but they can be used between the backend and the browser when a two-way channel is needed. The API key lives only in the backend; the browser does not call the Claude API directly.

  7. Why does putting rules in CLAUDE.md have no effect on a chatbot that calls the Messages API?

    Show answer

    CLAUDE.md is a Claude Code mechanism (and the Agent SDK's when it loads project configuration sources). The Messages API is stateless and only sees what the request sends: system, messages, tools. The chatbot's rules must be in system, and mandatory rules must be in code (permission checks in tools, output validation).

  8. A team wants every developer to use the same model version in Claude Code on Bedrock. How do you configure it and why?

    Show answer

    The opus/sonnet aliases change over time and on Bedrock may point to a different version than the Claude API. Pin with the ANTHROPIC_DEFAULT_OPUS_MODEL / ANTHROPIC_DEFAULT_SONNET_MODEL variables in the env of shared settings or managed settings, or set the full model ID; restrict the choices with availableModels. New models have breaking changes and different behavior, so changing the model must go through an eval like a code change.

  9. Name 4 prompt versioning practices for a production feature.

    Show answer

    Keep prompts in the repo and review them through PRs; attach a version and log prompt_version along with the model ID, effort and request ID; run an eval comparing the old and new versions before shipping; make configuration allow rolling back the prompt version; change only one variable at a time (prompt or model).

  10. The deploy-tools plugin declares "dependencies": ["secrets-vault"]. What does that mean? Which command invokes the plugin's deploy skill?

Show answer

secrets-vault is a plugin that must be enabled for deploy-tools to work; a name without a marketplace is looked up in the plugin's own marketplace, and the depended-on plugin is enabled along with it. The plugin's components are namespaced by the plugin name, so the skill runs as /deploy-tools:deploy.

  1. Distinguish a workflow from an agent according to the Building effective agents article. Give one example of each.
Show answer

Workflow: LLMs and tools are orchestrated through predefined code paths, for example routing tickets by type and then calling a specialized prompt. Agent: the LLM dynamically directs its own process and tool usage, for example finding why a test fails in an unfamiliar repo and fixing it. Choose a workflow when the steps are known in advance and predictability is needed; an agent when the number of steps is not known in advance and errors can be detected and recovered from.

  1. Why does a manager + subagent architecture help an agent that researches 30 documentation sources do better than a single agent? What is the cost?
Show answer

Each subagent reads a few sources in its own context and returns a structured summary, so the manager's context does not bloat or drift; work can run in parallel, use cheaper models for reading, and limit permissions by role. The cost: more total tokens, harder debugging, summaries can lose detail; the manager must check that worker results come with evidence.

  1. A customer requires the agent's files and commands to run inside their VPC, but wants Anthropic to operate the agent loop. Which deployment model do you choose?
Show answer

Managed Agents with a self-hosted sandbox: the loop runs at Anthropic, tools (bash, files, code) run on the customer's infrastructure, and the worker only connects outbound to receive work. Note that tool results still go back to the control plane for the model to read. If the data must not leave the VPC in any form, everything must be self-hosted (Agent SDK, hand-written loop) with the model accessed through an allowed platform.

  1. Compare client-side tools and server-side tools. Why can an internal stock lookup tool not be a server-side tool?
Show answer

A client-side tool is executed by your code (harness) after the model returns tool_use; a server-side tool (web search, web fetch, code execution) runs on Anthropic's infrastructure and its result is right in the response. The internal inventory system sits behind a firewall that Anthropic's infrastructure cannot reach; it must be a custom tool in the application or an MCP server you host.

  1. Your stdio MCP server works when tested by hand, but Claude Code reports a connection error. The code contains print("loaded config"). What is the problem?
Show answer

With stdio, stdout is the JSON-RPC channel; the server must not write anything to stdout other than MCP messages. print() injects stray text into the stream and breaks the protocol. Log to stderr (print(..., file=sys.stderr) or a logger configured to write to stderr).

  1. When do you choose Streamable HTTP over stdio for an MCP server? Which security measures are needed?
Show answer

When the server is shared by many clients and applications and deployed as an independent service. Measures per the spec: validate the Origin header to prevent DNS rebinding, bind only to 127.0.0.1 when running locally, authenticate every connection; on top of that, the server's credentials have only enough permissions for its tools, and every call is logged.

  1. Choose between a built-in tool, a custom tool, a Skill and an MCP server for: (a) the team's standard changelog writing process; (b) a stock lookup shared by 4 applications; (c) reading files in a repo; (d) a shipping fee function used only in one chatbot.
Show answer

(a) Skill: teaches how to do a process, loaded when needed. (b) MCP server: reused across many applications, maintained independently. (c) Built-in tool (Read/Grep in Claude Code or the Agent SDK). (d) A custom tool in the chatbot: logic tied to one application, no need for an extra service.

  1. Why is asking the model again "are you sure?" not a way to verify output?
Show answer

The new answer is also probabilistically generated text, which can be just as confident and still wrong; the confidence in the text is not a calibrated probability of being right. Verification must use an independent source: run tests, query real data, compare citations against the original documents, run evals on labeled data.

  1. List the 5 layers of checks on a response before using the result to issue a refund.
Show answer

(1) stop_reason is end_turn, handling refusal and max_tokens. (2) Parse safely (structured outputs, JSON.parse in try/catch). (3) Validate the schema with Zod/Pydantic. (4) Business rules: the order belongs to the authenticated user, the amount does not exceed the order value. (5) Ground against sources and route to human review when over a threshold; limited retries with error feedback.

  1. Distinguish a jailbreak (direct injection) from indirect injection according to the docs. What are the main measures for each?
Show answer

Jailbreak/direct injection: the user is the attacker, trying to bypass the policy; measures: a harmlessness screen with a lightweight model and structured outputs, input validation, a system prompt that states boundaries and how to refuse, handling repeat offenders. Indirect: the user is trusted but third-party content contains instructions; measures: put external content in tool_result, state the source, policy in the system prompt, JSON-encode, least privilege, screen tool output.

  1. Why should you not put your own instructions in a tool_result?
Show answer

Claude is trained to be skeptical of instructions that appear in tool results, because that is where untrusted content enters. Your instructions placed there may be ignored or treated as an injection. Send instructions in the user turn after the tool_result, or use a mid-conversation system message on models that support it.

  1. The screening turn with Haiku 5.5 returns stop_reason: "refusal". What should the code treat the input as?
Show answer

Treat it as harmful (per the docs), because the safety classifier refused the screening request itself, so there is no verdict to read. Likewise, any unclear screening result should be blocked to be safe (fail closed) rather than let through.

Hands-on Exercises

Exercise 1: Self-assessment against the blueprint

Build a table of the 8 domains with the sub-skills and weights from the exam guide. For each skill, rate yourself 1–3 and note the course lesson to reread.

Expected output: a self-assessment table; a list of your 5 weakest skills with a review plan before taking the Day 10 practice exam.

Exercise 2: Cost-controlled vision

Write a script that sends 5 screenshots of your application to Claude to list UI bugs. Run it twice: with the original images and with images downscaled to a long edge of 1,000 px.

Expected output: a table of visual tokens (calculated by hand and measured with count_tokens), estimated cost, the quality difference between the two runs; a conclusion on whether to downscale.

Exercise 3: Moving a job to the Message Batches API

Take the ticket classification job from Day 5, Exercise 2 (or 200 hypothetical tickets). Move it to the Message Batches API with custom_id, handling all 4 result.type values.

Expected output: separate scripts for creating the batch and reading the results; a table comparing cost and completion time with realtime calls.

Exercise 4: Inventory MCP server

Write a stdio MCP server with 2 tools (check_stock, list_low_stock) and 1 resource, using mock data. Add it to Claude Code with claude mcp add and ask Claude "Which SKUs are running low in the Hanoi warehouse?".

Expected output: the server code; a screenshot of /mcp showing the server; one deliberate attempt adding a print() to stdout, with a note on the error you hit.

Exercise 5: The output checking layer

Write an acceptRefund function (or equivalent) with all 5 layers from Part 4.2. Write tests for the cases: max_tokens, refusal, broken JSON, wrong schema, order not owned by the user, amount exceeding the order.

Expected output: the function and 6 passing tests; a note on which layer catches which case.

Exercise 6: Red-team your chatbot

Add a harmlessness screen and the untrusted content policy to the ticket classification assistant from the Day 8 capstone. Prepare 10 direct jailbreak inputs and 5 documents containing indirect injection (passed through tool_result).

Expected output: a table of the 15 cases: which layer blocked each one, or whether it got through; proposed additional layers for the cases that got through.

References


Next lesson →