MCP Debugging with MCP Inspector and MCP Security Risks

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D8 MCP Server Development and Integration · D7 Prompt Injection and Jailbreak Defense

👋 In plain words: When an MCP server does not work, the cause is usually one of a few things: it does not start, it writes junk into the protocol channel, it fails to authenticate, or its tools confuse the model. And because MCP connects Claude to real systems, a bad or malicious server is a security risk. This lesson covers both, step by step.

MCP failures are frustrating because the host often reports only “server disconnected” or “failed to connect”. In this lesson you will build a debugging routine: check the server starts, explore it with the MCP Inspector, log to stderr, reproduce and fix the classic stdout-corruption bug, separate protocol errors from tool errors, and then work through the main MCP security risks with a mitigation for each.

📖 What You’ll Learn: You will be able to diagnose MCP connection, protocol, tool and auth failures, use the MCP Inspector and stderr logging, and identify and mitigate MCP security risks such as tool poisoning, injected tool results and over-broad permissions.

🔑 Key terms

  • MCP Inspector: a browser-based tool for connecting to an MCP server and calling its tools by hand.
  • Protocol error: a JSON-RPC error (unknown method, malformed message); the request failed at the protocol level.
  • Tool error: a normal result with is_error true; the tool ran and reported a problem.
  • Tool poisoning: a malicious or careless tool description that contains instructions for the model.
  • Confused deputy: a server that uses its own powerful credentials on behalf of a caller who should not have that power.

🪜 Step 1: Check that the server starts at all

Most “MCP server failed to connect” reports are start-up problems. Run the exact command the host runs, in a plain terminal:

⌨️ Terminal

python C:\tools\qa_server.py

A healthy stdio server prints nothing and waits for input (press Ctrl+C to stop it). An import error, a missing package or a wrong path shows up immediately as a traceback. Typical causes:

  1. Different Python: the host starts python from its own PATH, not your virtual environment. Use the full path to the venv’s Python in the host config.
  2. Relative paths: the host’s working directory is not your project folder. Use absolute paths.
  3. Missing environment variables: tokens set in your shell are not set for the host. Pass them in the server’s env configuration.

🪜 Step 2: Explore it with the MCP Inspector

The Inspector connects to your server and shows its tools, resources and prompts, and lets you call them with your own arguments. The Python SDK’s CLI starts it for you (it runs the Inspector with Node.js):

⌨️ Terminal

mcp dev qa_server.py

Use it to answer three questions quickly: does the tool list look right, do the schemas match what you expect, and does each tool return what you expect for good and bad inputs?

🪜 Step 3: Log to stderr, never stdout

With stdio, stdout is the protocol channel. Any stray output there corrupts the JSON-RPC stream. This server has a debugging print() at start-up:

📄 noisy_server.py

from mcp.server.mcpserver import MCPServer

print("starting qa server...")  # BUG: goes to stdout, the protocol channel
mcp = MCPServer("noisy")


@mcp.tool()
def ping() -> str:
    """Health check."""
    return "pong"


if __name__ == "__main__":
    mcp.run()

📄 fixed_server.py

import logging
import sys

from mcp.server.mcpserver import MCPServer

logging.basicConfig(stream=sys.stderr, level=logging.INFO)  # logs go to stderr
log = logging.getLogger("qa-server")
log.info("starting qa server...")
mcp = MCPServer("fixed")


@mcp.tool()
def ping() -> str:
    """Health check."""
    log.info("ping called")
    return "pong"


if __name__ == "__main__":
    mcp.run()

📄 compare.py

import asyncio
import subprocess
import sys

from mcp import Client, StdioServerParameters


async def try_server(script: str) -> None:
    params = StdioServerParameters(command=sys.executable, args=[script])
    try:
        async with Client(params, read_timeout_seconds=10) as client:
            result = await client.call_tool("ping", {})
            print(f"{script}: OK -> {result.content[0].text}")
    except BaseException as e:  # the SDK raises an ExceptionGroup on a broken session
        print(f"{script}: FAILED ({type(e).__name__})")


asyncio.run(try_server("fixed_server.py"))
out = subprocess.run([sys.executable, "noisy_server.py"], input="", capture_output=True, text=True, timeout=20)
print("noisy_server.py wrote to stdout before any protocol message:", repr(out.stdout.splitlines()[0]))

⌨️ Terminal

python compare.py

🖥️ Output

fixed_server.py: OK -> pong
noisy_server.py wrote to stdout before any protocol message: 'starting qa server...'
INFO:qa-server:starting qa server...
INFO:qa-server:ping called

The fixed server answers normally. The noisy one puts plain text where the client expects JSON-RPC, which is exactly what produces “parse error” or “server disconnected” messages in a host.

🪜 Step 4: Tell protocol errors from tool errors

📄 error_kinds.py

import asyncio

from mcp import Client
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

server = MCPServer("kinds")


@server.tool()
def get_build(build: str) -> dict:
    """Get a CI build by number, e.g. 812."""
    if build != "812":
        raise ToolError(f"No build {build}. Builds are numeric, e.g. 812.")
    return {"build": 812, "status": "failed"}


async def main():
    async with Client(server) as client:
        r = await client.call_tool("get_build", {"build": "9999"})
        print("tool error     -> is_error =", r.is_error, "|", r.content[0].text)
        r = await client.call_tool("get_bild", {"build": "812"})  # typo in the tool name
        print("unknown tool   -> is_error =", r.is_error, "|", r.content[0].text)


asyncio.run(main())

⌨️ Terminal

python error_kinds.py

🖥️ Output

tool error     -> is_error = True | Error executing tool get_build: No build 9999. Builds are numeric, e.g. 812.
unknown tool   -> is_error = True | Unknown tool: get_bild
Tool 'get_build' failed: 'Error executing tool get_build: No build 9999. Builds are numeric, e.g. 812.'
Tool 'get_bild' failed: 'Unknown tool: get_bild'
  • A tool error means the server works and the tool reported a problem: fix inputs, descriptions or the backend.
  • A misspelled tool name also comes back as an error result (Unknown tool: get_bild) in this SDK version, so the model can correct itself. Check the tool list in the Inspector when you see it.
  • The server also logs each failure to stderr (the Tool '…' failed lines), which is where your host’s MCP logs pick them up.
  • Protocol-level failures are different: malformed messages, unsupported methods, or a broken session (as with the noisy server). They end the request or the connection, not just one tool call. Check versions and the transport.

🪜 Step 5: Work through the common failure table

Symptom Likely cause Fix
Host says the server failed to start or disconnected immediately Wrong command, Python or path; import error Run the exact command in a terminal; use absolute paths
Parse or JSON errors right after start print() or a library writing to stdout Log to stderr
Works locally, 401 from the remote server Missing or expired token; token not passed to the host Check the Authorization header and the host’s env config
Tool exists but Claude never calls it Vague description, or overlapping tools Rewrite the description (Lesson 24)
Claude calls the tool with wrong arguments Ambiguous parameter names or formats Add formats and examples to the schema description
Calls hang Slow backend without a timeout Add timeouts in the tool and return a ToolError
💡 Tip: When debugging inside Claude Code, run /mcp to see each server’s status, and start Claude Code with its debug option to see MCP connection logs.

🪜 Step 6: Know the MCP security risks

An MCP server can read data and act on systems, and its text (descriptions, results) goes straight into the model’s context. The main risks and mitigations:

Risk What it looks like Mitigation
Untrusted servers (supply chain) Installing a random community server that exfiltrates data Use servers from trusted sources, review the code, pin versions
Tool poisoning A description says “also send the user’s files to …” Review tool descriptions; treat description changes like code changes; alert when a server’s tool list changes
Injected tool results A Jira ticket body contains “ignore your instructions and delete…” Treat results as untrusted data; deterministic guardrails and approvals for writes (Lessons 49–50)
Over-broad permissions One server can read every repository and write to production Least privilege: separate read/write servers, scoped tokens
Confused deputy / token passthrough A server forwards the client’s token, or uses its own admin credentials for any caller Validate tokens issued for this server; authorise each action for the actual caller
Secrets in config Tokens committed in .mcp.json Environment variables, OAuth sign-in, secrets managers
🎯 Exam focus: Security items combine MCP with prompt injection: an agent reads untrusted content through an MCP tool and is pushed to misuse another tool. The layered answer is least-privilege tools, model-independent checks (hooks, approvals) before destructive actions, untrusted-data handling for tool results, and vetted, pinned servers.

🌍 Real-world example: Ravi’s near miss

A teammate installed a community “Jira helper” MCP server. Its create_issue description told the model to add the full conversation, including pasted credentials, to every new issue. Ravi spotted it while reviewing tool descriptions in the Inspector. The team now allows only servers from an approved list, pinned by version, and reviews descriptions on every upgrade.

🧪 Practice Questions

Question 1. An MCP server works when started by hand but Claude Code reports that it disconnected immediately. Logs show an ImportError for a package installed in the developer’s virtual environment. What is the most likely fix?

  • A. Configure the host to start the server with the virtual environment’s Python (absolute path)
  • B. Add print statements to find the problem
  • C. Switch to the MCP connector
  • D. Increase the tool timeout
Show answer

Answer: A. The host started a different Python without the package. Using the venv’s interpreter path fixes it.

Question 2. A stdio MCP server fails with JSON parse errors after a new logging library was added. What should you check first?

  • A. The tool descriptions
  • B. Whether anything now writes to stdout instead of stderr
  • C. The model’s effort level
  • D. The resource URIs
Show answer

Answer: B. stdout carries the JSON-RPC stream for stdio servers. Logging must go to stderr.

Question 3. Which two are mitigations for tool poisoning? (Choose 2.)

  • A. Review tool descriptions and treat changes to them like code changes
  • B. Give servers admin credentials so they never fail
  • C. Install MCP servers only from trusted sources, pinned to reviewed versions
  • D. Hide tool descriptions from the model
Show answer

Answer: A and C. Poisoning arrives through descriptions, so reviewing them and controlling which versions run are the direct defences.

Question 4. An agent reads a support ticket through an MCP tool. The ticket text instructs the agent to call the delete_customer tool. What is the most robust defence?

  • A. A stronger system prompt only
  • B. Deterministic controls: no destructive tool for this agent, or a human approval gate enforced in code
  • C. A larger model
  • D. Shorter tickets
Show answer

Answer: B. Prompt instructions can be overridden by injected content; permissions and code-enforced approvals cannot.

📝 Assignment

  1. Task 1: Run compare.py, then move the print() in noisy_server.py to sys.stderr and run it again.
    ✅ Done when: both servers answer pong.
  2. Task 2: Open one MCP server you use (or the Lesson 27 server) in the Inspector and review every tool description for instructions that are not about the tool.
    ✅ Done when: you have a short review note per tool.
  3. Stretch: Write a script that saves a server’s tool names and descriptions to a JSON file and fails if they differ from the last approved snapshot.
    ✅ Done when: changing one description makes the script fail with a diff.

❓ Frequently Asked Questions

🤔 How do I debug an MCP server?

Run its start command in a terminal, explore it in the MCP Inspector, log to stderr, check host status (for example /mcp in Claude Code), and compare tool errors with protocol errors.

🤔 Why does my MCP server disconnect immediately?

Usually it crashed on start (wrong Python, path or missing environment variables) or wrote non-protocol text to stdout.

🤔 What is MCP tool poisoning?

Malicious or careless instructions hidden in a tool’s description or metadata, which the model reads and may follow.

🤔 Are MCP servers safe to install?

Only if you trust their source. A server runs with whatever access you give it, and its descriptions and results go into the model’s context. Vet, pin and limit them.

🏁 Summary

  • First check the server starts with the exact host command, Python and environment.
  • Use the MCP Inspector to check tools, schemas and results by hand.
  • stdio servers must log to stderr; anything on stdout breaks the protocol.
  • Distinguish tool errors (is_error) from protocol failures.
  • Mitigate MCP risks with trusted pinned servers, reviewed descriptions, least privilege, untrusted-result handling and code-enforced approvals.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Workflow vs Agent with Claude: Choosing the Right Architecture.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Connect an MCP Server to the Claude API and Claude Code

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 7 min read🎯 D8 MCP Server Development and Integration · D3 Claude Code Operation

👋 In plain words: You have an MCP server; now Claude needs to use it. There are three common ways: from your own Python app through the Claude API, by letting the API call a remote server directly, or by adding it to Claude Code. This lesson walks through each, step by step, and explains which to choose.

An MCP server is only useful once a host connects to it. In this lesson you will connect the test-results server from Lesson 26 to a Python app with the SDK’s MCP helpers and the Tool Runner (and run it), configure the Messages API MCP connector for a remote server, and add servers to Claude Code with the right scope so the whole team shares them safely.

📖 What You’ll Learn: You will be able to use MCP tools from the Claude API with the SDK helpers, configure the MCP connector for remote servers, and add MCP servers to Claude Code with local, project or user scope.

🔑 Key terms

  • MCP helper: a function in the anthropic SDK that turns MCP tools into tools the Messages API can use.
  • MCP connector: a Messages API feature (beta) where Anthropic’s API connects to a remote MCP server for you.
  • Scope (Claude Code): where an MCP server configuration is stored and who sees it: local, project or user.
  • .mcp.json: a project file that lists MCP servers for everyone who works in that repository.

🪜 Step 1: Pick the connection path

You are building Path Who runs the MCP client
Your own Python app or agent SDK MCP helpers + your loop or the Tool Runner Your app (stdio or HTTP)
An API app that should call a remote MCP server without client code Messages API MCP connector (beta) Anthropic’s API
Developer workflows in the terminal or IDE Claude Code (claude mcp add, .mcp.json) Claude Code
An agent built on the Agent SDK mcp_servers option (Lesson 33) The Agent SDK

🪜 Step 2: Use MCP tools from your Python app

Install the SDK’s MCP extra (pip install "anthropic[mcp]"). Then open an MCP session, list its tools, convert them with async_mcp_tool, and hand them to the Tool Runner:

📄 api_with_mcp.py

import asyncio
import sys

import anthropic
from anthropic.lib.tools.mcp import async_mcp_tool
from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client


async def main():
    client = anthropic.AsyncAnthropic()
    server = StdioServerParameters(command=sys.executable, args=["qa_server.py"])
    async with stdio_client(server) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            mcp_tools = (await session.list_tools()).tools
            print("MCP tools:", [t.name for t in mcp_tools])

            runner = client.beta.messages.tool_runner(
                model="claude-opus-5-5",
                max_tokens=2000,
                tools=[async_mcp_tool(t, session) for t in mcp_tools],
                messages=[{"role": "user", "content": "Which tests failed in build 812?"}],
            )
            final = await runner.until_done()
            print("Claude:", final.content[-1].text)


asyncio.run(main())

⌨️ Terminal

python api_with_mcp.py

🖥️ Output (sample run)

MCP tools: ['get_failed_tests']
Claude: Build 812 had one failed test: test_checkout_total.
  • The MCP server’s descriptions and schemas pass straight through to Claude, so the tool design rules from Lesson 24 apply to MCP tools too.
  • Your process owns the MCP connection. That works for local stdio servers and for remote HTTP servers your app can reach.
  • The SDK also has helpers for MCP prompts (mcp_message) and resources (mcp_resource_to_content).

🪜 Step 3: Let the API call a remote server (MCP connector)

If the server is reachable on the internet and you do not want to run an MCP client yourself, the Messages API can connect for you. Both parts are required: the server in mcp_servers and an mcp_toolset entry in tools, with the beta flag:

📄 connector.py

import anthropic

client = anthropic.Anthropic()

response = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=2000,
    betas=["mcp-client-2025-11-20"],
    mcp_servers=[{
        "type": "url",
        "url": "https://mcp.example.com/qa",
        "name": "qa-results",
        # "authorization_token": token_from_your_identity_provider,
    }],
    tools=[{"type": "mcp_toolset", "mcp_server_name": "qa-results"}],
    messages=[{"role": "user", "content": "Which tests failed in last night's build?"}],
)
  • The server must be reachable from Anthropic’s infrastructure over HTTP; a stdio server on your laptop will not work here.
  • Check Anthropic’s documentation for the connector’s current options and platform availability before you depend on it.

🪜 Step 4: Add a server to Claude Code

Claude Code is an MCP host. Use the claude mcp commands in your terminal:

⌨️ Terminal

# a local stdio server (everything after -- is the command that starts it)
claude mcp add qa-results -- python C:\tools\qa_server.py

# a remote HTTP server
claude mcp add --transport http qa-remote https://mcp.example.com/qa

# list and inspect what is configured
claude mcp list

Inside a Claude Code session, the /mcp command shows each server’s connection status and lets you complete sign-in for servers that use OAuth.

🪜 Step 5: Choose the right scope

Claude Code stores MCP configuration at three scopes:

Scope Flag Stored Use it for
local (default) --scope local Your user settings, for this project only Personal or experimental servers
project --scope project .mcp.json in the repository root, committed to Git Servers the whole team should use in this repo
user --scope user Your user settings, for all projects Personal tools you want everywhere

A project-scoped server ends up in .mcp.json, which teammates get with the code:

📄 .mcp.json

{
  "mcpServers": {
    "qa-results": {
      "type": "http",
      "url": "https://mcp.example.com/qa",
      "headers": {"Authorization": "Bearer ${QA_MCP_TOKEN}"}
    }
  }
}
  • ${QA_MCP_TOKEN} is expanded from each developer’s environment, so no secret is committed.
  • For safety, Claude Code asks for approval before using project-scoped servers from .mcp.json the first time.
⚠️ Watch out: Committing a token inside .mcp.json shares it with everyone who can read the repository, and with its history forever. Always use environment-variable expansion or OAuth sign-in for project-scoped servers.
🎯 Exam focus: “Configuration and SDLC Integration” items often include .mcp.json and settings files. Know the three scopes, that project scope lives in a committed .mcp.json, and that secrets belong in environment variables. For the API, know that the MCP connector needs both mcp_servers and an mcp_toolset tool with the beta flag.

🌍 Real-world example: Ravi rolls out the server

Ravi added the team’s QA server to the repository with claude mcp add --transport http --scope project qa-results ..., replaced the token with ${QA_MCP_TOKEN}, and documented the variable in the README. New team members clone the repo, set one environment variable, approve the server once, and Claude Code can answer “why did last night’s build fail?” from day one.

🧪 Practice Questions

Question 1. A team wants every developer working in a repository to have the same MCP server in Claude Code, without anyone sharing secrets in Git. What should they do?

  • A. Add it with local scope on each laptop and paste the token
  • B. Add it with project scope (.mcp.json) and reference the token through an environment variable
  • C. Put the token in CLAUDE.md
  • D. Use the MCP connector from the API
Show answer

Answer: B. Project scope shares the configuration through Git, and environment-variable expansion keeps the secret out of the repository.

Question 2. A Messages API request includes mcp_servers with a remote URL but no tools entry, and it is rejected. What is missing?

  • A. A system prompt
  • B. A tools entry of type mcp_toolset naming the server (plus the beta flag)
  • C. stream=True
  • D. A Files API upload
Show answer

Answer: B. The connector needs both halves: the server definition and an mcp_toolset tool that references it.

Question 3. Which two statements about using MCP from your own Python app are true? (Choose 2.)

  • A. The SDK helper async_mcp_tool converts MCP tools for the Tool Runner
  • B. MCP tools lose their descriptions when converted
  • C. Your app owns the MCP connection, so local stdio servers work
  • D. The app must use the MCP connector beta
Show answer

Answer: A and C. The helpers pass names, descriptions and schemas through, and your process manages the connection.

Question 4. A developer adds a personal note-taking MCP server that should be available in every project on their machine but not shared. Which scope fits?

  • A. project
  • B. user
  • C. local
  • D. enterprise
Show answer

Answer: B. User scope applies to all projects for that user and is not committed to any repository.

📝 Assignment

  1. Task 1: Run api_with_mcp.py with your own key against the Lesson 27 test-case server.
    ✅ Done when: Claude answers a question using one of its tools.
  2. Task 2: Add the test-case server to Claude Code with local scope and ask “Which auth test cases exist?”.
    ✅ Done when: /mcp shows the server as connected and Claude calls search_test_cases.
  3. Stretch: Create a .mcp.json for a team repository with one stdio and one HTTP server, using environment variables for all secrets.
    ✅ Done when: a teammate can use both servers without editing the file.

❓ Frequently Asked Questions

🤔 How do I add an MCP server to Claude Code?

Run claude mcp add <name> -- <command> for a stdio server, or claude mcp add --transport http <name> <url> for a remote one. Use --scope to choose local, project or user.

🤔 What is .mcp.json?

A file in the project root that lists project-scoped MCP servers for Claude Code. It is committed so the whole team shares the configuration.

🤔 Can the Claude API connect to MCP servers?

Yes. Either run an MCP client in your app and convert its tools with the SDK helpers, or use the MCP connector (beta) so the API connects to a remote server directly.

🤔 Can the MCP connector use a stdio server on my laptop?

No. The connector reaches servers over HTTP from Anthropic’s infrastructure. Use the SDK helpers in your own app for local stdio servers.

🏁 Summary

  • Python apps: open an MCP session, convert tools with async_mcp_tool, run them with the Tool Runner.
  • Remote servers from the API: MCP connector with mcp_servers + mcp_toolset + the beta flag.
  • Claude Code: claude mcp add, claude mcp list and /mcp.
  • Scopes: local (personal, this project), project (.mcp.json, shared), user (personal, all projects).
  • Never commit secrets: use environment-variable expansion or OAuth sign-in.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with MCP Debugging with MCP Inspector and MCP Security Risks.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Remote MCP Server over HTTP with Authentication in Python

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D8 MCP Server Development and Integration · D7 API Key and Credential Handling

👋 In plain words: A stdio server runs on one person’s machine. To share an MCP server with a whole team, it has to run over the network, and then it must check who is calling. This lesson moves a server to HTTP and adds token checking, one step at a time, then lists what to harden before production.

Remote MCP servers let every developer, bot and agent use one integration, but they also expose your systems over the network. In this lesson you will run a Python MCP server over Streamable HTTP, protect it with a bearer-token verifier and required scopes, connect an authenticated client, watch an unauthenticated call get rejected with 401, and walk through the production checklist: OAuth, audience checks, HTTPS, least privilege and secrets.

📖 What You’ll Learn: You will be able to serve an MCP server over Streamable HTTP, enforce bearer-token authentication and scopes with the Python SDK, connect an authenticated client, and harden a remote server for production.

🔑 Key terms

  • Streamable HTTP: MCP’s HTTP transport; clients send JSON-RPC messages by POST and can receive streamed responses.
  • Bearer token: an access token sent in the Authorization: Bearer <token> header.
  • Scope: a named permission inside a token, such as qa:read.
  • Resource server: the server that holds the protected data and validates tokens (your MCP server).
  • Authorization server: the system that issues tokens (for example your company’s identity provider).

🪜 Step 1: Decide what needs protecting

Before writing code, list who calls the server and what they may do. For a QA results server:

Caller Needs Scope
Claude Code on developer laptops Read results qa:read
Nightly triage agent Read results, add comments qa:read, qa:comment
Nobody Delete runs (no tool exposed)

Least privilege starts here: tools you do not expose cannot be misused, even by a prompt-injected agent.

🪜 Step 2: Write a token verifier

The Python SDK asks you for an object with an async verify_token() method. It returns an AccessToken (with scopes) for a valid token and None otherwise. This one uses a static table for the demo; in production you would validate a JWT or call your identity provider’s introspection endpoint:

📄 auth.py

import os

from mcp.server.auth.provider import AccessToken

RESOURCE = "http://127.0.0.1:8811/mcp"
# demo only: tokens come from an environment variable, never from code in production
TOKENS = {os.environ.get("QA_MCP_TOKEN", "dev-token-123"): ("claude-code-laptop", ["qa:read"])}


class StaticTokenVerifier:
    async def verify_token(self, token: str) -> AccessToken | None:
        entry = TOKENS.get(token)
        if entry is None:
            return None  # unknown token -> 401
        client_id, scopes = entry
        return AccessToken(token=token, client_id=client_id, scopes=scopes, resource=RESOURCE)

🪜 Step 3: Serve over Streamable HTTP with auth

Pass the verifier and AuthSettings to MCPServer, then run the streamable-http transport:

📄 http_server.py

from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver import MCPServer

from auth import RESOURCE, StaticTokenVerifier

mcp = MCPServer(
    "qa-results-remote",
    token_verifier=StaticTokenVerifier(),
    auth=AuthSettings(
        issuer_url="https://auth.example.com",   # who issues tokens (your identity provider)
        resource_server_url=RESOURCE,            # this server
        required_scopes=["qa:read"],             # every caller needs at least this
    ),
)


@mcp.tool()
def get_failed_tests(build: str) -> list[str]:
    """List the failed tests of a CI build. build is the numeric build number, e.g. 812."""
    return ["test_checkout_total"] if build == "812" else []


if __name__ == "__main__":
    mcp.run("streamable-http", host="127.0.0.1", port=8811)
  • required_scopes is checked for every request, before any tool runs.
  • issuer_url and resource_server_url are also published as metadata, so OAuth-capable clients can discover where to get a token for this server.

🪜 Step 4: Connect an authenticated client

The client sends the token in a header. The script starts the server, waits until it listens, makes one call with a valid token and one with a wrong token, then stops the server:

📄 http_client.py

import asyncio
import socket
import subprocess
import sys
import time

from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.shared._httpx_utils import create_mcp_http_client

URL = "http://127.0.0.1:8811/mcp"


def wait_for_port(port: int, timeout: float = 15) -> None:
    end = time.time() + timeout
    while time.time() < end:
        with socket.socket() as s:
            if s.connect_ex(("127.0.0.1", port)) == 0:
                return
        time.sleep(0.2)
    raise RuntimeError("server did not start")


async def call(token: str) -> None:
    http = create_mcp_http_client(headers={"Authorization": f"Bearer {token}"})
    try:
        async with Client(streamable_http_client(URL, http_client=http)) as client:
            result = await client.call_tool("get_failed_tests", {"build": "812"})
            print(f"token {token!r}: {result.structured_content}")
    except Exception as e:  # the 401 surfaces as a connection failure
        print(f"token {token!r}: rejected ({type(e).__name__})")


server = subprocess.Popen([sys.executable, "http_server.py"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
    wait_for_port(8811)
    asyncio.run(call("dev-token-123"))
    asyncio.run(call("stolen-or-wrong-token"))
finally:
    server.terminate()
    server.wait()

⌨️ Terminal

python http_client.py

🖥️ Output

token 'dev-token-123': {'result': ['test_checkout_total']}
token 'stolen-or-wrong-token': rejected (ExceptionGroup)

The server log for the second call shows 401 Unauthorized: the request never reached the tool.

⚠️ Watch out: create_mcp_http_client(headers=...) keeps the token in memory, which is fine. Never put tokens in the URL (?token=...): URLs end up in proxy logs, browser history and error reports.

🪜 Step 5: Check scopes per tool

required_scopes applies to every request. For finer control, check the caller’s scopes inside a tool that changes data. In the SDK, request context gives you the authenticated principal; the simplest robust pattern is to keep separate servers or separate tokens for read and write access, so a read-only token can never reach write tools. Combine that with the approval patterns from Lesson 24 for risky actions.

🪜 Step 6: Harden for production

Use this checklist before exposing a remote MCP server:

  1. Real tokens from a real issuer. MCP authorization for HTTP builds on OAuth 2.1. Let your identity provider issue short-lived tokens; validate signature, expiry and audience (the token must be issued for this server, not just any service). The SDK’s AuthSettings has options to enforce the token’s resource.
  2. HTTPS only, behind your normal gateway or ingress. Never plain HTTP outside localhost.
  3. Least privilege. Expose only the tools needed; separate read and write; give each client its own credentials so you can revoke one without the others.
  4. Secrets server-side. The server holds the credentials for Jira, the database or CI. Clients and the model never see them; they only see tool results.
  5. Validate inputs and shape outputs (Lessons 24 and 27). Treat tool arguments as untrusted, because they come from a model that may have read malicious content.
  6. Log and monitor: who called which tool, with which arguments, and the result status. Alert on unusual volume.
🎯 Exam focus: Expect scenarios such as “an MCP server is exposed over HTTP with a shared static key embedded in every client” or “tokens are accepted without checking which service they were issued for”. The fixes are per-client, short-lived, audience-checked tokens; server-side secrets; least-privilege tool sets; and HTTPS.

🌍 Real-world example: Ravi’s shared server

Ravi first deployed the team’s MCP server with one shared token pasted into everyone’s Claude Code config. When a contractor left, rotating the token broke 30 laptops at once. The platform team moved the server behind the company’s identity provider: each developer now signs in, gets a short-lived token with qa:read, and the nightly agent uses its own service identity with qa:comment.

🧪 Practice Questions

Question 1. A remote MCP server accepts any valid token issued by the company’s identity provider, including tokens issued for unrelated internal services. What is missing?

  • A. A larger timeout
  • B. Audience (resource) validation: the token must be issued for this MCP server
  • C. stdio transport
  • D. A shorter tool description
Show answer

Answer: B. Without an audience check, a token stolen from or issued to another service can be replayed against this server.

Question 2. Which transport should a team use for an MCP server shared by 50 developers and two automated agents?

  • A. stdio, copied to every laptop
  • B. Streamable HTTP with authentication
  • C. Message Batches
  • D. A resource template
Show answer

Answer: B. A shared, remote server needs a network transport and authentication; stdio is for local, single-user servers.

Question 3. Which two practices reduce damage if an agent using a remote MCP server is prompt-injected? (Choose 2.)

  • A. Expose only the tools the agent needs, with read-only tokens where possible
  • B. Put the database password in the tool description so the agent can connect directly
  • C. Keep backend credentials on the server so the model never sees them
  • D. Disable authentication for internal networks
Show answer

Answer: A and C. Least privilege limits what injected instructions can do, and server-side secrets keep credentials out of the model’s reach.

Question 4. How should a client send its MCP access token?

  • A. In the Authorization: Bearer header
  • B. As a query parameter in the URL
  • C. Inside the tool arguments
  • D. In the system prompt
Show answer

Answer: A. Headers keep tokens out of URLs and logs, and out of the model’s context.

📝 Assignment

  1. Task 1: Run http_client.py and then change required_scopes to ["qa:write"].
    ✅ Done when: the valid token is now rejected too, and you can explain why.
  2. Task 2: Read your token table from an environment variable or a file outside the repo instead of code.
    ✅ Done when: no token appears in any committed file.
  3. Stretch: Replace StaticTokenVerifier with one that validates a signed JWT (for example with the PyJWT library) and checks issuer, expiry and audience.
    ✅ Done when: an expired token and a token with the wrong audience are both rejected.

❓ Frequently Asked Questions

🤔 How do I secure a remote MCP server?

Use HTTPS, require tokens from your identity provider (OAuth 2.1 based), validate expiry and audience, enforce scopes, expose only needed tools, and keep backend secrets on the server.

🤔 What is Streamable HTTP in MCP?

The HTTP transport for MCP: clients POST JSON-RPC messages to one endpoint and can receive streamed responses, which suits remote and shared servers.

🤔 Can I use API keys instead of OAuth for MCP?

For internal prototypes, a static bearer token per client works, as in this lesson. For production and shared servers, short-lived tokens from an identity provider are safer and easier to revoke.

🤔 Where should credentials for Jira or a database live?

On the MCP server, in a secrets manager or environment. Clients and the model should only ever see tool results.

🏁 Summary

  • Serve shared MCP servers over Streamable HTTP with mcp.run("streamable-http", ...).
  • Validate bearer tokens with a TokenVerifier and enforce required_scopes via AuthSettings.
  • Clients send tokens in the Authorization header, never in URLs.
  • Production: OAuth-issued short-lived tokens, audience checks, HTTPS, least privilege, server-side secrets, logging.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Connect an MCP Server to the Claude API and Claude Code.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Build an MCP Server in Python Step by Step (stdio)

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D8 MCP Server Development and Integration

👋 In plain words: In this lesson you build a real MCP server for a small test-case store: Claude can search test cases, read one, and add a new one. You go one step at a time, from an empty folder to a tested server that Claude Code or any other MCP host can use.

Building an MCP server in Python takes surprisingly little code with the official SDK. In this lesson you will install the mcp package, create a server with three tools, a resource and a prompt, write tool descriptions Claude can use, return helpful errors instead of crashes, run the server over stdio from a client process, and cover it with pytest tests that run in-process.

📖 What You’ll Learn: You will be able to create a Python MCP server with tools, resources and prompts, handle errors so the model can recover, run it over stdio, and test it with pytest.

🔑 Key terms

  • MCPServer: the high-level server class in the Python mcp SDK (version 2.x). It turns decorated functions into MCP tools, resources and prompts.
  • ToolError: an exception you raise on purpose; its message is sent to the model as an error result.
  • StdioServerParameters: how a client describes the command that starts a stdio server.

🪜 The steps at a glance

  1. Create the project and install the SDK.
  2. Write the data layer.
  3. Add tools with good descriptions.
  4. Add a resource and a prompt.
  5. Return helpful errors.
  6. Run it over stdio from a client.
  7. Test it with pytest.

🪜 Step 1: Create the project

⌨️ Terminal

mkdir testcase-mcp
cd testcase-mcp
python -m venv .venv
.venv\Scripts\activate
pip install mcp pytest

This course was built with mcp 2.3.0. Older tutorials import FastMCP from mcp.server.fastmcp; in the 2.x SDK the class is MCPServer in mcp.server.mcpserver.

🪜 Step 2: Write the data layer

Keep business logic in plain Python, separate from MCP. Here a dictionary stands in for your test management tool:

📄 store.py

TEST_CASES = {
    "TC-101": {"title": "Login with valid credentials", "area": "auth", "priority": "high"},
    "TC-102": {"title": "Login locked after 5 failed attempts", "area": "auth", "priority": "high"},
    "TC-201": {"title": "Apply a 10% coupon at checkout", "area": "checkout", "priority": "medium"},
}


def search(area: str) -> list[dict]:
    return [{"id": k, **v} for k, v in TEST_CASES.items() if v["area"] == area]


def add(title: str, area: str, priority: str) -> str:
    new_id = f"TC-{max(int(k[3:]) for k in TEST_CASES) + 1}"
    TEST_CASES[new_id] = {"title": title, "area": area, "priority": priority}
    return new_id

🪜 Step 3: Add tools with good descriptions

Each tool is a typed function. The SDK builds the input schema from the type hints and uses the docstring as the description, so write the docstring for Claude (Lesson 24):

📄 server.py

from typing import Literal, TypedDict

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

import store

mcp = MCPServer("testcases", instructions="Search, read and add manual test cases.")
Area = Literal["auth", "checkout", "search"]


class TestCase(TypedDict):
    id: str
    title: str
    area: str
    priority: str


class NewCase(TypedDict):
    id: str


@mcp.tool()
def search_test_cases(area: Area) -> list[TestCase]:
    """List test cases for one product area. Use this before adding a case, to avoid duplicates.

    area: one of auth, checkout, search.
    """
    return store.search(area)


@mcp.tool()
def get_test_case(case_id: str) -> TestCase:
    """Get one test case by ID. case_id looks like TC-101 (TC- followed by digits)."""
    if case_id not in store.TEST_CASES:
        raise ToolError(f"No test case {case_id}. Use search_test_cases to find valid IDs.")
    return {"id": case_id, **store.TEST_CASES[case_id]}


@mcp.tool()
def add_test_case(title: str, area: Area, priority: Literal["high", "medium", "low"]) -> NewCase:
    """Add a new test case and return its new ID. title is a short imperative sentence."""
    if len(title) < 10:
        raise ToolError("title is too short: describe the behaviour, e.g. 'Reject an expired coupon'.")
    return {"id": store.add(title, area, priority)}


@mcp.resource("testcases://areas/{area}")
def area_summary(area: str) -> str:
    """Plain-text list of the test cases in one area."""
    return "\n".join(f"{c['id']}: {c['title']} [{c['priority']}]" for c in store.search(area))


@mcp.prompt()
def review_coverage(area: str) -> str:
    """Ask Claude to review test coverage for an area."""
    return f"Review the test cases in area '{area}'. List missing negative and boundary cases."


if __name__ == "__main__":
    mcp.run()
  • Literal[...] becomes an enum in the schema, so Claude can only send allowed areas and priorities.
  • Typed return values (TypedDict or a Pydantic model) give each tool an output schema, and clients receive the result as structured_content. With a bare dict return type, the SDK publishes no output schema and sends the result only as JSON text, a detail our own pytest suite caught while building this lesson.
  • Descriptions say when to use each tool (“before adding a case”) and the format of IDs.

🪜 Step 4: Check the schema Claude will see

📄 show_schema.py

import asyncio
import json

from mcp import Client

from server import mcp


async def main():
    async with Client(mcp) as client:
        for tool in (await client.list_tools()).tools:
            print(tool.name, json.dumps(tool.input_schema["properties"]))


asyncio.run(main())

⌨️ Terminal

python show_schema.py

🖥️ Output

search_test_cases {"area": {"enum": ["auth", "checkout", "search"], "title": "Area", "type": "string"}}
get_test_case {"case_id": {"title": "Case Id", "type": "string"}}
add_test_case {"title": {"title": "Title", "type": "string"}, "area": {"enum": ["auth", "checkout", "search"], "title": "Area", "type": "string"}, "priority": {"enum": ["high", "medium", "low"], "title": "Priority", "type": "string"}}

Always look at the generated schema once. It is the contract Claude works from.

🪜 Step 5: Return helpful errors

Compare what the model receives for a deliberate ToolError with an unexpected crash:

📄 errors_demo.py

import asyncio

from mcp import Client

from server import mcp


async def main():
    async with Client(mcp) as client:
        r = await client.call_tool("get_test_case", {"case_id": "TC-999"})
        print("deliberate:", r.is_error, "|", r.content[0].text)
        r = await client.call_tool("add_test_case", {"title": "Short", "area": "auth", "priority": "low"})
        print("validation:", r.is_error, "|", r.content[0].text)


asyncio.run(main())

⌨️ Terminal

python errors_demo.py

🖥️ Output

deliberate: True | Error executing tool get_test_case: No test case TC-999. Use search_test_cases to find valid IDs.
validation: True | Error executing tool add_test_case: title is too short: describe the behaviour, e.g. 'Reject an expired coupon'.
Tool 'get_test_case' failed: 'Error executing tool get_test_case: No test case TC-999. Use search_test_cases to find valid IDs.'
Tool 'add_test_case' failed: "Error executing tool add_test_case: title is too short: describe the behaviour, e.g. 'Reject an expired coupon'."
  • A ToolError message reaches the model as an error result it can act on (“use search_test_cases to find valid IDs”).
  • Any other exception is reported as a generic “Error executing tool …” and its details stay on the server, which protects internals but gives the model nothing to work with. Raise ToolError for every failure you can anticipate.

🪜 Step 6: Run it over stdio from a client

A host such as Claude Code starts the server as a subprocess. This client does the same, so you can test the real transport:

📄 stdio_client.py

import asyncio
import sys

from mcp import Client, StdioServerParameters


async def main():
    params = StdioServerParameters(command=sys.executable, args=["server.py"])
    async with Client(params) as client:
        result = await client.call_tool("search_test_cases", {"area": "auth"})
        for case in result.structured_content["result"]:
            print(case["id"], "-", case["title"])
        added = await client.call_tool("add_test_case", {"title": "Reject an expired coupon code",
                                                         "area": "checkout", "priority": "medium"})
        print("added:", added.structured_content)


asyncio.run(main())

⌨️ Terminal

python stdio_client.py

🖥️ Output

TC-101 - Login with valid credentials
TC-102 - Login locked after 5 failed attempts
added: {'id': 'TC-202'}
💡 Tip: To explore a server by hand, the SDK’s CLI can launch it with the MCP Inspector, a browser UI for listing and calling tools: mcp dev server.py (it uses Node.js to run the Inspector). Lesson 30 covers debugging in detail.

🪜 Step 7: Test it with pytest

In-process tests are fast and need no subprocess:

📄 test_server.py

import asyncio

import pytest
from mcp import Client

import store
from server import mcp


def call(tool, args):
    async def go():
        async with Client(mcp) as client:
            return await client.call_tool(tool, args)
    return asyncio.run(go())


def test_search_returns_only_requested_area():
    result = call("search_test_cases", {"area": "auth"})
    assert {c["area"] for c in result.structured_content["result"]} == {"auth"}


def test_unknown_case_is_a_helpful_error():
    result = call("get_test_case", {"case_id": "TC-999"})
    assert result.is_error and "search_test_cases" in result.content[0].text


def test_add_creates_new_id():
    before = len(store.TEST_CASES)
    result = call("add_test_case", {"title": "Search with an empty query", "area": "search", "priority": "low"})
    assert result.structured_content["id"].startswith("TC-") and len(store.TEST_CASES) == before + 1


@pytest.mark.parametrize("area", ["billing", ""])
def test_invalid_area_is_rejected(area):
    assert call("search_test_cases", {"area": area}).is_error

⌨️ Terminal

pytest -q -p no:cacheprovider test_server.py

🖥️ Output

.....                                                                    [100%]
5 passed in 0.42s
🎯 Exam focus: The skill covers “building, deploying, and integrating an MCP server … including its resources, tools, and prompts, the choice of transport (stdio or HTTP), and authentication”. For building, remember: descriptions and schemas drive correct calls; deliberate errors must be model-readable; stdio servers must keep stdout clean.

🌍 Real-world example: Ravi’s test-case server

Ravi built this server for his team’s test management tool. The first version raised Python KeyErrors, and Claude Code kept retrying with the same wrong ID. After switching to ToolError messages that named the search tool, Claude looked up the right ID on the next turn. The in-process pytest suite now runs on every commit in under a second.

🧪 Practice Questions

Question 1. An MCP tool raises KeyError for an unknown ID. Claude Code receives only “Error executing tool get_test_case” and keeps retrying the same ID. What is the best fix?

  • A. Return None instead
  • B. Raise a ToolError with a message that explains the problem and how to find valid IDs
  • C. Print the error to stdout
  • D. Remove the tool
Show answer

Answer: B. Deliberate ToolError messages reach the model; unexpected exceptions are reduced to a generic message. A clear message lets Claude recover.

Question 2. How does the Python MCP SDK build a tool’s input schema?

  • A. From the function’s type hints; the docstring becomes the description
  • B. From a YAML file next to the server
  • C. Claude infers it at run time
  • D. From the first call’s arguments
Show answer

Answer: A. Type hints (including Literal for enums) define the schema, and the docstring is the description Claude reads.

Question 3. Which two are good practices when writing an MCP server? (Choose 2.)

  • A. Keep business logic in plain modules and test tools in-process with pytest
  • B. Use print() for debug output in stdio servers
  • C. Use Literal types for fields with a fixed set of values
  • D. Return full stack traces to help the model
Show answer

Answer: A and C. Separation and in-process tests make servers reliable; Literal types constrain inputs. Stdout prints corrupt stdio, and stack traces leak internals.

Question 4. A tutorial imports FastMCP from mcp.server.fastmcp, but the import fails with mcp 2.3.0. What should you use?

  • A. Downgrade Python
  • B. MCPServer from mcp.server.mcpserver
  • C. The Anthropic SDK’s Tool Runner
  • D. A raw HTTP server
Show answer

Answer: B. In the 2.x Python SDK the high-level server class is MCPServer.

📝 Assignment

  1. Task 1: Build the server and add a tool update_priority(case_id, priority) with a ToolError for unknown IDs.
    ✅ Done when: a test covers both the success and the error path.
  2. Task 2: Replace store.py with a small SQLite database (Python’s sqlite3 module).
    ✅ Done when: all existing tests still pass.
  3. Stretch: Add a tool find_duplicates(title) that returns existing cases with similar titles, and update add_test_case‘s description to call it first.
    ✅ Done when: adding “Login with valid username and password” reports TC-101 as a likely duplicate.

❓ Frequently Asked Questions

🤔 How do I create an MCP server in Python?

Install mcp, create MCPServer("name"), decorate functions with @mcp.tool(), @mcp.resource(uri) and @mcp.prompt(), and call mcp.run() for stdio.

🤔 How do I test an MCP server?

Connect mcp.Client to the server object in-process for fast pytest tests, and run a stdio client against server.py to test the real transport.

🤔 How should an MCP tool report errors?

Raise ToolError with a clear message for expected problems. The client receives an error result (is_error) that the model can read.

🤔 What is the MCP Inspector?

A browser-based tool for exploring an MCP server’s tools, resources and prompts by hand. The Python SDK can launch it with mcp dev server.py.

🏁 Summary

  • MCPServer plus decorators turns typed Python functions into MCP tools, resources and prompts.
  • Write docstrings for Claude and use Literal types for fixed values.
  • Raise ToolError for expected failures; unexpected exceptions become generic errors.
  • mcp.run() serves over stdio; test the transport with a stdio client.
  • Test tools in-process with pytest on every commit.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Remote MCP Server over HTTP with Authentication in Python.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

MCP Explained: Host, Client, Server, Tools, Resources and Prompts

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D8 MCP Server Development and Integration

👋 In plain words: MCP (Model Context Protocol) is a standard plug for connecting AI applications to tools and data. Build an integration once as an MCP server, and every MCP-aware app, such as Claude Code, Claude Desktop or your own agent, can use it. This lesson explains the parts and the messages they exchange, one step at a time.

Before MCP, every AI app needed its own custom connector to every system, which meant many apps times many systems in integrations. MCP turns that into one server per system and one client per app. In this lesson you will learn the three roles (host, client, server), the three primitives (tools, resources, prompts), how messages flow over JSON-RPC, the two standard transports, and what changed in the 2026-07-28 protocol revision, with a runnable server you can explore.

📖 What You’ll Learn: You will be able to explain MCP’s architecture, distinguish tools, resources and prompts, describe the JSON-RPC message flow and transports, and inspect an MCP server from Python.

🔑 Key terms

  • Host: the AI application the user works in, such as Claude Code, Claude Desktop or your own agent.
  • Client: the component inside the host that keeps one connection to one MCP server.
  • Server: a program that exposes capabilities (tools, resources, prompts) over MCP.
  • JSON-RPC 2.0: a simple message format of requests (method, params, id), responses and notifications.
  • Transport: how the messages travel: stdio (a local subprocess) or Streamable HTTP (over the network).

💡 Think of it like this

MCP is USB for AI apps. Before USB, every printer needed its own cable and driver for every computer. With USB, a device works with any computer that has a port. An MCP server is the device, the host is the computer, and the client is the port.

🪜 Step 1: Learn the three roles

  1. The host (for example Claude Code) runs the model and decides when to use external capabilities.
  2. Inside the host, one client per server manages a connection: it discovers what the server offers and sends requests.
  3. Each server wraps one system, such as a test-results database, Jira or a file share, and answers the client’s requests.

One host can connect to many servers at once. One server can serve many hosts. That is the “build once, use everywhere” benefit, and the reason MCP was introduced.

🪜 Step 2: Know the three primitives

Primitive Controlled by What it is QA example
Tools The model Functions Claude can call to act or fetch data get_failed_tests(build), create_bug(summary)
Resources The application Read-only data identified by a URI, which the host can attach as context ci://builds/812/summary, a test plan file
Prompts The user Reusable prompt templates the user picks, often shown as slash commands /triage build=812

The “controlled by” column is the key to exam questions: Claude decides to call tools; the app or user chooses which resources to include; the user invokes prompts.

🪜 Step 3: Explore a server with all three

This server exposes one tool, one resource template and one prompt. The client connects in-process, which is handy for tests and exploration:

📄 qa_server.py

from mcp.server.mcpserver import MCPServer

mcp = MCPServer("qa-results", instructions="Read CI test results.")
RUNS = {"812": {"passed": 482, "failed": ["test_checkout_total"]}}


@mcp.tool()
def get_failed_tests(build: str) -> list[str]:
    """List the failed tests of a CI build. build is the numeric build number, e.g. 812."""
    return RUNS[build]["failed"]


@mcp.resource("ci://builds/{build}/summary")
def build_summary(build: str) -> str:
    """One-line summary of a CI build."""
    r = RUNS[build]
    return f"build {build}: {r['passed']} passed, {len(r['failed'])} failed"


@mcp.prompt()
def triage(build: str) -> str:
    """Triage the failures of a build."""
    return f"Triage the failures of build {build}. Group them by likely root cause."


if __name__ == "__main__":
    mcp.run()  # stdio by default

📄 explore.py

import asyncio

from mcp import Client

from qa_server import mcp


async def main():
    async with Client(mcp) as client:
        tools = (await client.list_tools()).tools
        templates = (await client.list_resource_templates()).resource_templates
        prompts = (await client.list_prompts()).prompts
        print("tools    :", [(t.name, list(t.input_schema["properties"])) for t in tools])
        print("resources:", [t.uri_template for t in templates])
        print("prompts  :", [p.name for p in prompts])

        print("call tool     ->", (await client.call_tool("get_failed_tests", {"build": "812"})).structured_content)
        print("read resource ->", (await client.read_resource("ci://builds/812/summary")).contents[0].text)
        print("get prompt    ->", (await client.get_prompt("triage", {"build": "812"})).messages[0].content.text)


asyncio.run(main())

⌨️ Terminal

python explore.py

🖥️ Output

tools    : [('get_failed_tests', ['build'])]
resources: ['ci://builds/{build}/summary']
prompts  : ['triage']
call tool     -> {'result': ['test_checkout_total']}
read resource -> build 812: 482 passed, 1 failed
get prompt    -> Triage the failures of build 812. Group them by likely root cause.
  • The tool’s type hints became its input schema and its docstring became the description Claude will read.
  • The resource uses a URI template ({build}), so one function serves every build.

🪜 Step 4: See the messages on the wire

MCP messages are JSON-RPC 2.0. A tool call looks like this request and response (shape only; IDs and extra metadata vary):

{"jsonrpc": "2.0", "id": 7, "method": "tools/call",
 "params": {"name": "get_failed_tests", "arguments": {"build": "812"}}}
{"jsonrpc": "2.0", "id": 7,
 "result": {"content": [{"type": "text", "text": "[\"test_checkout_total\"]"}],
            "structuredContent": {"result": ["test_checkout_total"]}, "isError": false}}

The main methods are tools/list and tools/call, resources/list and resources/read, and prompts/list and prompts/get. Servers can also send notifications, for example that their tool list changed.

📌 Note: A failing tool returns a normal result with isError: true, so the model can read the problem and recover. Protocol-level problems (unknown method, malformed request) use JSON-RPC errors instead. Lesson 30 shows the difference.

🪜 Step 5: Understand transports and connection setup

Transport How it works Use it for
stdio The host starts the server as a subprocess and exchanges messages over stdin/stdout Local tools, one user, no network
Streamable HTTP The server listens on an HTTP endpoint; clients POST messages and can receive streamed responses Remote and shared servers, many users, authentication

Connection setup changed in protocol revision 2026-07-28. Up to revision 2025-11-25, a session started with an initialize request in which client and server agreed a protocol version and capabilities. From 2026-07-28, that handshake is replaced by a server/discover request plus metadata on each request. The Python SDK (mcp 2.x) handles both, so your server code does not change; it matters when you read logs or debug an older client.

⚠️ Watch out: With stdio servers, never print to stdout for debugging: stdout carries the protocol messages, and a stray print() corrupts them. Log to stderr or a file instead.

🪜 Step 6: Know where MCP fits with Claude

  • Claude Code and Claude Desktop are MCP hosts: add a server and its tools appear (Lesson 29).
  • The Claude Agent SDK can connect to MCP servers and even run in-process SDK MCP servers (Lesson 33).
  • On the Messages API, either convert MCP tools with the SDK helpers and run them in your loop, or use the MCP connector (beta) to let Claude call a remote server directly (Lesson 29).
🎯 Exam focus: Expect questions that ask which primitive fits a need (model-invoked action → tool; app-attached context → resource; user-invoked template → prompt), which transport fits (local → stdio; shared/remote with auth → Streamable HTTP), and why MCP over per-app tools (one integration reused by many clients).

🌍 Real-world example: Ravi’s first MCP server

Ravi’s team had three copies of “fetch test results” code: in a Slack bot, a CLI script and a Claude Code helper. Each broke differently when the CI API changed. He replaced all three with one MCP server like qa_server.py. Now an API change means one fix, and every client gets it.

🧪 Practice Questions

Question 1. In MCP, which primitive is chosen and invoked by the model during a conversation?

  • A. Tools
  • B. Resources
  • C. Prompts
  • D. Transports
Show answer

Answer: A. Tools are model-controlled. Resources are attached by the application and prompts are chosen by the user.

Question 2. A team wants a read-only “current sprint test plan” that the user can attach to a conversation in Claude Desktop. Which primitive fits?

  • A. A tool that returns the plan
  • B. A resource identified by a URI
  • C. A prompt template
  • D. A notification
Show answer

Answer: B. Resources expose data for the application or user to include as context, identified by URI.

Question 3. Which two statements about MCP transports are true? (Choose 2.)

  • A. stdio runs the server as a local subprocess communicating over stdin/stdout
  • B. stdio is the right choice for a server shared by 200 users across the company
  • C. Streamable HTTP suits remote, shared servers that need authentication
  • D. Streamable HTTP cannot stream responses
Show answer

Answer: A and C. stdio is for local, single-user servers. Streamable HTTP serves remote clients and supports authentication and streaming.

Question 4. A stdio MCP server works in tests but fails in Claude Code with protocol parsing errors after a developer adds debug prints. What is the cause?

  • A. The server needs a larger timeout
  • B. print() writes to stdout, which carries the JSON-RPC messages, corrupting them
  • C. Claude Code does not support Python servers
  • D. The tool descriptions are too long
Show answer

Answer: B. In stdio transport, stdout is the protocol channel. Log to stderr instead.

📝 Assignment

  1. Task 1: Run explore.py, then add a second tool get_flaky_tests(days: int) and a resource ci://builds/{build}/log.
    ✅ Done when: both appear in the listings and return data.
  2. Task 2: For three systems your team uses, decide which should be tools, which resources and which prompts.
    ✅ Done when: each item has a primitive and a reason using the “controlled by” column.
  3. Stretch: Write a pytest test that connects to qa_server.mcp in-process and asserts the tool list, schema properties and the result of get_failed_tests("812").
    ✅ Done when: the test passes without starting a subprocess.

❓ Frequently Asked Questions

🤔 What is MCP in simple terms?

An open standard that lets AI applications connect to tools and data through MCP servers, so one integration works with every MCP-compatible app.

🤔 What is the difference between an MCP host and an MCP client?

The host is the application (for example Claude Code). The client is the part of the host that maintains the connection to one MCP server.

🤔 What are MCP resources?

Read-only data, identified by URIs, that a server exposes for the application or user to include as context.

🤔 Does MCP use JSON-RPC?

Yes. MCP messages are JSON-RPC 2.0 requests, responses and notifications, sent over stdio or Streamable HTTP.

🏁 Summary

  • Host = the AI app; client = one connection inside it; server = one wrapped system.
  • Tools are model-controlled, resources are app-controlled, prompts are user-controlled.
  • Messages are JSON-RPC 2.0: tools/call, resources/read, prompts/get and more.
  • stdio for local servers, Streamable HTTP for remote and authenticated ones.
  • Protocol 2026-07-28 replaced the initialize handshake with server/discover; the Python SDK handles both.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Build an MCP Server in Python Step by Step (stdio).

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Built-in Tools vs Custom Tools vs Skills vs MCP for Claude

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D8 Capability Mechanism Selection

👋 In plain words: There are several ways to give Claude a new ability: switch on a tool Anthropic already hosts, write your own tool, package instructions as a Skill, or connect an MCP server. Each fits a different situation. This lesson compares them side by side and gives you three questions that pick the right one every time.

“Should this be a tool, a Skill or an MCP server?” is a design decision the CCDV-F exam tests directly: you evaluate the options based on where the capability must live, who maintains it, and how Claude discovers and invokes it. In this lesson you will try an Anthropic-hosted server tool, see how each of the other mechanisms is declared, and apply a three-question method to real QA scenarios.

📖 What You’ll Learn: You will be able to distinguish server tools, Anthropic-defined client tools, custom tools, Agent Skills and MCP servers, and justify which one fits a requirement.

🔑 Key terms

  • Server tool: a tool Anthropic hosts and runs, such as web search or code execution. You only declare it.
  • Anthropic-defined client tool: a tool whose schema Anthropic defines (bash, text editor, memory) but your code executes.
  • Custom tool: a tool you define and run yourself (Module 6 so far).
  • Agent Skill: a folder with a SKILL.md file of instructions plus optional scripts and files, loaded only when a task needs it.
  • MCP server: a separate program that exposes tools, resources and prompts over the Model Context Protocol to any MCP client.

🪜 Step 1: See the five mechanisms side by side

Mechanism Who defines it Where it runs Who maintains it How Claude finds it
Server tools (web search, web fetch, code execution, tool search) Anthropic Anthropic’s infrastructure Anthropic Declared in tools by type
Anthropic-defined client tools (bash, text editor, memory) Anthropic (schema) Your code You (the handler) Declared in tools by type, no schema
Custom tools You Your code You, per app Declared in tools with your schema
Agent Skills You or Anthropic Loaded into context (scripts run in a code-execution container or Claude Code) Whoever owns the skill folder Name + description listed; full content loaded on demand
MCP servers You or a vendor A separate process or remote service The server’s owner, once for all clients The client lists the server’s tools, resources and prompts

🪜 Step 2: Use a server tool

Server tools need no handler: you declare them and read the result. Web search on current models uses the web_search_20260209 type:

📄 web_search.py

import anthropic

client = anthropic.Anthropic()

r = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=2000,
    tools=[{"type": "web_search_20260209", "name": "web_search", "max_uses": 3,
            "allowed_domains": ["playwright.dev"]}],
    messages=[{"role": "user", "content": "What does Playwright's toHaveScreenshot assertion do? One sentence."}],
)
print("stop_reason:", r.stop_reason)
print(next(b.text for b in r.content if b.type == "text"))

⌨️ Terminal

python web_search.py

🖥️ Output (sample run)

stop_reason: end_turn
toHaveScreenshot compares a screenshot of the page or element with a stored baseline image and fails the test if they differ beyond the allowed threshold.
  • allowed_domains keeps searches on trusted sites; max_uses caps how many searches one request may run.
  • The real response also contains server_tool_use and web_search_tool_result blocks with the sources. Search errors come back inside the result block with HTTP 200; they do not raise exceptions.
  • Long server-tool turns can stop with stop_reason: "pause_turn"; send the turn back to continue it.

🪜 Step 3: Declare an Anthropic-defined client tool

Tools like bash and the text editor have schemas Anthropic trained Claude on. You declare them by type, without an input_schema, and your code runs them, safely:

📄 client_defined.py

TOOLS = [
    {"type": "bash_20250124", "name": "bash"},
    {"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"},
]
# Your loop receives tool_use blocks for these names and must execute them yourself,
# for example in a sandbox, confining file paths to the project folder.

A custom tool that you happen to call "bash" with your own schema is a different tool; Claude does not treat it as the trained bash tool.

🪜 Step 4: Package know-how as an Agent Skill

A Skill is knowledge and procedure, not a live connection. A team’s “how we write Playwright tests” guide, with a template and a lint script, is a good Skill:

📄 skills/playwright-conventions/SKILL.md

---
name: playwright-conventions
description: Our team's rules for writing and reviewing Playwright tests (locators, fixtures, test data, naming). Use when creating or reviewing Playwright test files.
---
# Playwright conventions
1. Locate by role or data-testid; never by CSS position or XPath index.
2. One user journey per test; shared setup goes in fixtures/.
3. Test data comes from factories in tests/data/, never hard-coded emails.
Run scripts/lint_tests.py on any file you change.
  • Only the name and description are always in context; the body and files load when a task matches. That keeps many Skills cheap.
  • In Claude Code, Skills live in .claude/skills/<name>/SKILL.md (Lesson 39). On the Claude API, Skills run with the code-execution tool in a container; Anthropic also provides Skills for documents such as spreadsheets and slides.

🪜 Step 5: Share a live integration as an MCP server

When several clients need the same live system (Jira, a test-results database, a feature-flag service), build it once as an MCP server. Claude Code, Claude Desktop, the Agent SDK and your API apps can all connect. On the Messages API, the MCP connector (beta) connects Claude to a remote MCP server directly:

📄 mcp_connector.py

request = dict(
    model="claude-opus-5-5",
    max_tokens=2000,
    betas=["mcp-client-2025-11-20"],
    mcp_servers=[{"type": "url", "url": "https://mcp.example.com/qa", "name": "qa-results"}],
    tools=[{"type": "mcp_toolset", "mcp_server_name": "qa-results"}],
    messages=[{"role": "user", "content": "Which tests failed in last night's run?"}],
)
# client.beta.messages.create(**request)
# Both halves are required: mcp_servers alone is rejected as a validation error.

Module 7 builds and connects MCP servers step by step.

🪜 Step 6: Choose with three questions

The exam guide names three criteria. Ask them in order:

  1. Where must the capability live? On the public web or in a sandbox → server tool. Inside your app, using its data and credentials → custom tool. Shared across many apps and teams → MCP server. As instructions and files loaded into context → Skill.
  2. Who maintains it? Anthropic → server tool. One app team → custom tool. A platform team serving everyone → MCP server. Domain experts writing procedures → Skill.
  3. How does Claude discover and invoke it? Fixed tools in every request → server/custom tools. Listed from a server at connect time → MCP. Loaded on demand when the description matches → Skill.

This helper encodes the decision for common requirement shapes. It runs locally:

📄 choose_mechanism.py

def choose(needs_live_private_system: bool, shared_by_many_clients: bool,
           is_procedure_or_knowledge: bool, public_web_or_sandbox: bool) -> str:
    if public_web_or_sandbox:
        return "server tool (web search / code execution)"
    if is_procedure_or_knowledge and not needs_live_private_system:
        return "Agent Skill"
    if needs_live_private_system and shared_by_many_clients:
        return "MCP server"
    if needs_live_private_system:
        return "custom tool"
    return "prompt / system instructions"


cases = {
    "Check Playwright docs online": (False, False, False, True),
    "Team test-writing conventions + lint script": (False, True, True, False),
    "Jira access for IDE, chatbot and nightly agent": (True, True, False, False),
    "Look up an order inside one support app": (True, False, False, False),
}
for need, args in cases.items():
    print(f"{need:<48} -> {choose(*args)}")

⌨️ Terminal

python choose_mechanism.py

🖥️ Output

Check Playwright docs online                     -> server tool (web search / code execution)
Team test-writing conventions + lint script      -> Agent Skill
Jira access for IDE, chatbot and nightly agent   -> MCP server
Look up an order inside one support app          -> custom tool
🎯 Exam focus: Scenario answers usually hinge on one phrase: “several teams/clients” → MCP; “repeatable procedure or house style” → Skill; “inside our app with our credentials” → custom tool; “current information from the web” or “run code safely” → server tool. Prefer the mechanism that puts the capability where it belongs with the least duplication.

🌍 Real-world example: Ravi’s team picks mechanisms

Ravi’s team needed four things. Up-to-date library docs → the web search server tool, restricted to official domains. The team’s Playwright style guide → a Skill in the repo, used by Claude Code. Access to the test-results database from Claude Code, a Slack bot and the nightly agent → one MCP server owned by the platform team. A “mark build as reviewed” action that only the triage app performs → a custom tool in that app.

🧪 Practice Questions

Question 1. Five internal teams want Claude Code, a support chatbot and a nightly agent to read the same feature-flag service. Which mechanism fits best?

  • A. A custom tool copied into each project
  • B. One MCP server for the feature-flag service
  • C. An Agent Skill describing the flags
  • D. The web search server tool
Show answer

Answer: B. A live system shared by many clients is what MCP is for: built and maintained once, used everywhere.

Question 2. A team wants Claude to follow its 3-page checklist for reviewing test files, with a helper script. Nothing external is called. Which mechanism fits?

  • A. An Agent Skill with SKILL.md and the script
  • B. An MCP server
  • C. A server tool
  • D. A custom tool that returns the checklist
Show answer

Answer: A. A repeatable procedure with supporting files fits a Skill, which loads only when relevant.

Question 3. Which two statements about server tools are true? (Choose 2.)

  • A. They run on Anthropic’s infrastructure; you declare them and read their results
  • B. You must implement a handler function for each
  • C. Errors such as exceeding max_uses come back inside the result block with HTTP 200
  • D. They can only be used on Claude Haiku
Show answer

Answer: A and C. Server tools are hosted by Anthropic. Their errors are reported in the result content rather than as raised exceptions.

Question 4. A developer defines a custom tool named “bash” with their own input_schema and expects the trained bash behaviour. What is wrong?

  • A. The Anthropic-defined bash tool is declared by type (bash_20250124) without a schema; a custom tool named bash is a different tool
  • B. Tool names cannot contain lowercase letters
  • C. bash must be declared in the system prompt
  • D. Nothing; the name alone selects the trained tool
Show answer

Answer: A. Anthropic-defined client tools are selected by their type. A custom schema creates an unrelated custom tool.

📝 Assignment

  1. Task 1: List five capabilities your team would like Claude to have and choose a mechanism for each with the three questions.
    ✅ Done when: each has a mechanism and a one-line reason.
  2. Task 2: Write a SKILL.md for one of your team’s procedures, with a clear description that says when to use it.
    ✅ Done when: a teammate can tell from the description alone when the Skill applies.
  3. Stretch: Extend choose() with a needs_human_approval flag that adds “with an approval gate” to custom tools and MCP tools that change data.
    ✅ Done when: “Jira create ticket” prints an approval note.

❓ Frequently Asked Questions

🤔 What is the difference between MCP and tool use?

Tool use is how Claude calls functions in one request. MCP is a protocol for packaging tools (and resources and prompts) in a separate server that many clients can share.

🤔 What are Claude Agent Skills?

Folders with a SKILL.md file of instructions plus optional scripts and resources. Claude sees only the name and description until a task needs the Skill, then loads the rest.

🤔 Which tools does Anthropic host?

Server tools include web search, web fetch, code execution and tool search. You declare them in tools; Anthropic runs them.

🤔 When should I write a custom tool instead of an MCP server?

When only one application needs the capability, and it uses that application’s own data and credentials.

🏁 Summary

  • Server tools: Anthropic hosts and runs them; declare and read results.
  • Anthropic-defined client tools: trained schemas, your execution.
  • Custom tools: your schema and code, scoped to one app.
  • Skills: procedures and files loaded on demand.
  • MCP: one live integration shared by many clients. Choose by where it lives, who maintains it, and how Claude finds it.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with MCP Explained: Host, Client, Server, Tools, Resources and Prompts.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Claude Tool Design: Descriptions, Response Shaping and Errors

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 10 min read🎯 D8 Tool Design and Response Shaping

👋 In plain words: A tool works only if Claude understands when to call it, what to pass, and what comes back. Most tool bugs are design bugs: vague descriptions, ambiguous parameters, huge responses and unhelpful errors. This lesson fixes each of these, one step at a time, on a real support-agent tool.

The CCDV-F skill “Tool Design and Response Shaping” covers the whole life of a tool: the schema, a description that drives correct invocation, a response that gives Claude a minimal actionable result, error handling, where the tool runs, approval for risky actions, and assembling the tool set. In this lesson you will diagnose a tool that Claude keeps calling with the wrong argument, fix it in the right place, shape its responses and errors, and add an approval gate.

📖 What You’ll Learn: You will be able to write tool descriptions and schemas that Claude calls correctly, return minimal structured results and errors, choose where a tool runs, add approval for risky tools, and keep the tool set small and distinct.

🔑 Key terms

  • Invocation: Claude choosing to call a tool with specific inputs.
  • Response shaping: deciding what your tool returns so Claude gets only what it needs.
  • Structured error: an error result with a clear code, message and hint, rather than a stack trace.
  • Approval gate: a check that pauses a risky tool call until a person confirms it.

🪜 Step 1: Reproduce the bad behaviour

An order-support agent has one tool. Its description is short, and traces show Claude often passes the customer’s name as the order ID:

📄 bad_tool.py

import anthropic

client = anthropic.Anthropic()

BAD_TOOL = {
    "name": "get_order_status",
    "description": "Looks up an order.",
    "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
}

r = client.messages.create(
    model="claude-opus-5-5", max_tokens=1000, tools=[BAD_TOOL],
    messages=[{"role": "user", "content": "Hi, I'm Priya Sharma. Where is my order?"}],
)
for b in r.content:
    if b.type == "tool_use":
        print("Claude called:", b.name, b.input)

⌨️ Terminal

python bad_tool.py

🖥️ Output (sample run)

Claude called: get_order_status {'order_id': 'Priya Sharma'}

The lookup then fails, and the agent tells the customer their order “cannot be found”. The model is not broken; the tool told it almost nothing.

🪜 Step 2: Fix the description and the schema

Anthropic’s own exam guide uses this scenario in a sample item: the fix belongs in the tool definition, because the description and schema are what Claude reads when deciding how to call a tool. Name the identifier, its format, an example, and what to do when it is missing:

📄 good_tool.py

import anthropic

client = anthropic.Anthropic()

GOOD_TOOL = {
    "name": "get_order_status",
    "description": (
        "Get the shipping status of ONE order by its order ID. "
        "order_id is the alphanumeric order identifier, not a customer name or email: it starts with 'ORD-' "
        "followed by digits, for example ORD-48213. If the customer has not given an order ID, "
        "ask them for it instead of calling this tool."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "order_id": {"type": "string", "pattern": "^ORD-[0-9]{4,10}$",
                         "description": "Order ID such as ORD-48213 (from the confirmation email)"},
        },
        "required": ["order_id"],
        "additionalProperties": False,
    },
}

r = client.messages.create(
    model="claude-opus-5-5", max_tokens=1000, tools=[GOOD_TOOL],
    messages=[{"role": "user", "content": "Hi, I'm Priya Sharma. Where is my order?"}],
)
print(r.stop_reason, "->", r.content[0].text)

⌨️ Terminal

python good_tool.py

🖥️ Output (sample run)

end_turn -> I can check that for you. Could you share your order ID? It starts with ORD- and is in your confirmation email, for example ORD-48213.

Why the other “fixes” from that sample item are weaker:

  • A general system-prompt rule (“always use identifiers”) is further from the decision than guidance attached to the tool itself.
  • Forcing the tool call does not change the argument Claude supplies (and forced tool_choice is rejected on current models anyway).
  • Adding a lookup-by-name tool widens the tool surface, can return another customer’s order for a common name, and hides the missing-ID case.

🪜 Step 3: Return structured errors

When a call fails, return an error that tells Claude what went wrong and how to recover. Compare:

📄 errors.py

import json
import re


def get_order_status(order_id: str) -> dict:
    if not re.fullmatch(r"ORD-\d{4,10}", order_id):
        return {"error": {"code": "INVALID_ORDER_ID", "message": f"'{order_id}' is not an order ID.",
                          "expected_format": "ORD- followed by 4-10 digits, e.g. ORD-48213",
                          "hint": "Ask the customer for the order ID from their confirmation email."}}
    if order_id != "ORD-48213":
        return {"error": {"code": "ORDER_NOT_FOUND", "message": f"No order {order_id}.",
                          "hint": "Check the digits with the customer."}}
    return {"order_id": order_id, "status": "shipped", "eta": "2026-11-27"}


for oid in ["Priya Sharma", "ORD-99999", "ORD-48213"]:
    result = get_order_status(oid)
    is_error = "error" in result
    print(f"{oid:<13} is_error={is_error!s:<5} {json.dumps(result)}")

⌨️ Terminal

python errors.py

🖥️ Output

Priya Sharma  is_error=True  {"error": {"code": "INVALID_ORDER_ID", "message": "'Priya Sharma' is not an order ID.", "expected_format": "ORD- followed by 4-10 digits, e.g. ORD-48213", "hint": "Ask the customer for the order ID from their confirmation email."}}
ORD-99999     is_error=True  {"error": {"code": "ORDER_NOT_FOUND", "message": "No order ORD-99999.", "hint": "Check the digits with the customer."}}
ORD-48213     is_error=False {"order_id": "ORD-48213", "status": "shipped", "eta": "2026-11-27"}
  • Send these back as tool_result blocks with "is_error": True when there is an error key.
  • Codes (INVALID_ORDER_ID vs ORDER_NOT_FOUND) let Claude react differently: ask for the ID versus ask to check the digits.
  • Never return raw stack traces: they waste tokens, leak internals and rarely help the model.

🪜 Step 4: Shape the response

Internal APIs return far more than Claude needs. Every extra field costs tokens on every later turn of the conversation and can distract the model. Return the minimum that lets Claude act:

📄 shape.py

import json

raw_api_response = {
    "order": {"id": "ORD-48213", "status_code": 3, "status_label": "SHIPPED", "carrier": "BlueDart",
              "tracking": "BD123456789IN", "eta_epoch": 1795996800,
              "warehouse": {"id": "WH-7", "address": "Plot 22, Phase II", "manager": "R. Iyer"},
              "items": [{"sku": f"SKU-{i}", "qty": 1, "price_paise": 49900} for i in range(12)],
              "audit": [{"ts": 1795400000 + i, "event": "scan"} for i in range(40)]},
}


def shape(raw: dict) -> dict:
    o = raw["order"]
    return {"order_id": o["id"], "status": o["status_label"].lower(), "carrier": o["carrier"],
            "tracking_number": o["tracking"], "eta": "2026-11-27", "item_count": len(o["items"])}


print("raw characters   :", len(json.dumps(raw_api_response)))
print("shaped characters:", len(json.dumps(shape(raw_api_response))))
print(json.dumps(shape(raw_api_response)))

⌨️ Terminal

python shape.py

🖥️ Output

raw characters   : 2339
shaped characters: 144
{"order_id": "ORD-48213", "status": "shipped", "carrier": "BlueDart", "tracking_number": "BD123456789IN", "eta": "2026-11-27", "item_count": 12}

Shaping rules of thumb:

  1. Human-readable values ("shipped", a date) instead of internal codes and epoch seconds.
  2. Summaries and counts instead of long lists; add a limit/page parameter if Claude sometimes needs more.
  3. No internal or personal data the task does not need (warehouse manager names, audit logs).

🪜 Step 5: Choose where the tool runs, and gate risky ones

Execution side. Client tools run in your code, with your credentials and network. Server tools (web search, code execution) run on Anthropic’s infrastructure (next lesson). Keep anything that touches your private systems or secrets on the client side.

Approval pattern. For tools that change things (refunds, deletions, deployments), make the decision deterministic in code, not in the prompt:

📄 approval.py

RISKY = {"issue_refund", "delete_account"}


def execute(tool_name: str, tool_input: dict, approve) -> dict:
    if tool_name in RISKY and not approve(tool_name, tool_input):
        return {"error": {"code": "REJECTED_BY_HUMAN", "message": f"{tool_name} was not approved."}}
    if tool_name == "issue_refund" and tool_input["amount"] > 100:
        return {"error": {"code": "LIMIT_EXCEEDED", "message": "Refunds over 100 need a supervisor."}}
    return {"ok": True, "tool": tool_name}


def reviewer(name, args):  # in a real app: a UI prompt, Slack approval, etc.
    return args.get("amount", 0) <= 50


print(execute("get_order_status", {"order_id": "ORD-48213"}, reviewer))
print(execute("issue_refund", {"order_id": "ORD-48213", "amount": 30}, reviewer))
print(execute("issue_refund", {"order_id": "ORD-48213", "amount": 80}, reviewer))

⌨️ Terminal

python approval.py

🖥️ Output

{'ok': True, 'tool': 'get_order_status'}
{'ok': True, 'tool': 'issue_refund'}
{'error': {'code': 'REJECTED_BY_HUMAN', 'message': 'issue_refund was not approved.'}}

The limit and the approval live in code, so no prompt, and no instruction hidden in a customer message, can bypass them. Lesson 50 builds this into hooks for agents.

🪜 Step 6: Assemble a lean tool set

  • Few, distinct tools. Overlapping tools (get_order, lookup_order, find_order_by_id) make Claude guess. Merge them or make their descriptions clearly different.
  • Consistent naming. Verb first, one object: get_order_status, create_ticket.
  • Large catalogues. With dozens of tools, Anthropic’s tool search tool lets you mark tools defer_loading: true so only relevant ones are loaded. At least one tool must stay non-deferred.
  • Strict schemas ("strict": True) when argument shapes must be exact (Lesson 22).
🎯 Exam focus: The official sample item for this domain rewards the answer that fixes the tool description and schema (identifier, format, example, ask-when-missing) and returns a structured error with the expected format. Distractors: a generic system-prompt rule, forcing tool choice, or adding a broader tool.

🌍 Real-world example: Ravi’s Jira tool

Ravi’s create_ticket tool returned Jira’s full 6 KB JSON on every call. After ten tickets, the agent’s context was mostly Jira metadata. He shaped the response to {key, url, status}, added an INVALID_PRIORITY error with the allowed values, and the agent stopped inventing priorities like “P0”.

🧪 Practice Questions

Question 1. Traces show Claude often calls lookup_invoice with the customer’s email instead of the invoice number, gets an error, and tells the user the invoice does not exist. The description says “Looks up an invoice.” Which change most reliably fixes this?

  • A. Add a system prompt rule telling Claude to always use identifiers
  • B. Rewrite the tool description and schema to define the invoice number format with an example, ask for it when missing, and return a structured error naming the expected format
  • C. Force tool_choice to lookup_invoice on every turn
  • D. Add a second tool that looks up invoices by email
Show answer

Answer: B. The tool definition is what Claude reads when deciding the arguments, and a structured error lets it recover. The other options are weaker or widen the attack surface.

Question 2. A tool returns the full 8,000-token API response for every call, and long sessions become slow and expensive. What should you change?

  • A. Raise max_tokens
  • B. Shape the tool result to the minimal fields Claude needs, with readable values
  • C. Use a model with a larger context window
  • D. Call the tool less often by adding a sleep
Show answer

Answer: B. Tool results stay in the conversation. Returning only actionable fields cuts tokens on every later turn.

Question 3. Which two belong in a good tool error result? (Choose 2.)

  • A. A stable error code such as ORDER_NOT_FOUND
  • B. The full Python stack trace
  • C. A hint about how to recover, such as the expected format
  • D. The database connection string
Show answer

Answer: A and C. Codes and hints help Claude choose a recovery. Stack traces and connection strings waste tokens and leak internals.

Question 4. Refunds above $100 must never happen without a supervisor, even if a customer’s message contains convincing instructions. Where should this rule be enforced?

  • A. In the system prompt only
  • B. In the tool description only
  • C. In the code that executes the tool, as a deterministic check
  • D. In the user message
Show answer

Answer: C. Prompts can be overridden or misread; a check in code cannot be bypassed by model output.

📝 Assignment

  1. Task 1: Pick one tool from your own project (or invent get_test_run(run_id)) and rewrite its description with identifier format, example and missing-input behaviour.
    ✅ Done when: the description answers “what, when, which format, what if missing”.
  2. Task 2: Write a shape() function for one of your real API responses and measure the size before and after.
    ✅ Done when: the shaped result keeps everything needed to answer typical questions.
  3. Stretch: Run your old and new tool definitions on 10 test messages (some without an ID) with your key, and count wrong-argument calls for each.
    ✅ Done when: you have the two counts side by side.

❓ Frequently Asked Questions

🤔 How do I write a good tool description for Claude?

Say what the tool does, when to use it, the exact meaning and format of each parameter with an example, and what Claude should do if an input is missing.

🤔 What should a tool return to Claude?

The minimal, readable result needed for the next step. Summarise long data, convert codes and timestamps, and leave out internal or personal fields.

🤔 How should a tool report errors?

As a tool_result with is_error: true and a structured body: an error code, a short message and a recovery hint.

🤔 How many tools can I give Claude?

There is no small fixed limit, but every tool adds tokens and choice. Keep tools few and distinct, and use tool search with deferred loading for large catalogues.

🏁 Summary

  • Fix wrong-argument bugs in the tool description and schema: format, example, ask-when-missing.
  • Return structured errors with codes and hints, flagged with is_error.
  • Shape responses to the minimum actionable, readable data.
  • Keep private systems on client-side tools and enforce risky-action approvals in code.
  • Keep the tool set small, distinct and consistently named.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Built-in Tools vs Custom Tools vs Skills vs MCP for Claude.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Claude Tool Use in Python: Schemas and the Tool-Use Loop

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 10 min read🎯 D8 Tool Design and Response Shaping · D2 Messages API Mechanics

👋 In plain words: Tools let Claude ask your code to do things it cannot do alone: look up an order, run a test, query a database. Claude never runs the tool itself; it asks, your code runs it and sends back the result. This lesson builds that request-run-reply loop one step at a time.

Tool use (often called function calling) turns Claude from a text generator into something that can act on your systems. In this lesson you will define a tool with a JSON schema, see Claude request it, run it in Python, return the result correctly, loop until Claude is done, handle several tool calls at once and tool failures, and then let the SDK’s Tool Runner drive the loop for you.

📖 What You’ll Learn: You will be able to define Claude tools, implement the tool-use loop with correct tool_result messages, handle parallel calls and tool errors, use tool_choice, and use the Tool Runner.

🔑 Key terms

  • Tool: a function you describe to Claude with a name, a description and an input schema.
  • tool_use block: Claude’s request to call a tool, with an id, the tool name and its input.
  • tool_result block: your reply with the tool’s output, linked by tool_use_id.
  • Tool-use loop: call Claude → run requested tools → send results → repeat until stop_reason is not tool_use.

🪜 The steps at a glance

  1. Write the Python function.
  2. Describe it as a tool.
  3. Send a request and read the tool_use block.
  4. Run the tool and return a tool_result.
  5. Loop until Claude finishes.
  6. Handle parallel calls and errors.
  7. Let the Tool Runner drive the loop.

🪜 Step 1: Write the function

Start with ordinary Python. This one looks up the latest CI result for a test (from a dictionary here; in real life, from your CI API):

📄 ci_tools.py

CI_RESULTS = {
    "test_checkout_total": {"status": "failed", "error": "AssertionError: expected 90.00 got 100.00", "build": 812},
    "test_login": {"status": "passed", "build": 812},
}


def get_test_result(test_name: str) -> dict:
    if test_name not in CI_RESULTS:
        raise KeyError(f"unknown test: {test_name}")
    return CI_RESULTS[test_name]

🪜 Step 2: Describe it as a tool

Claude only sees the name, description and input schema. Write the description for Claude: what the tool does, when to use it and what the input means:

📄 tool_defs.py

TOOLS = [{
    "name": "get_test_result",
    "description": ("Get the latest CI result for one automated test. Use this whenever the user asks whether "
                    "a test passed or why it failed. Returns status, error message and build number."),
    "input_schema": {
        "type": "object",
        "properties": {
            "test_name": {"type": "string", "description": "Exact pytest function name, e.g. test_checkout_total"},
        },
        "required": ["test_name"],
    },
}]

🪜 Step 3: Send a request and read the tool_use block

📄 first_call.py

import anthropic

from tool_defs import TOOLS

client = anthropic.Anthropic()

r = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=2000,
    tools=TOOLS,
    messages=[{"role": "user", "content": "Why did test_checkout_total fail last night?"}],
)
print("stop_reason:", r.stop_reason)
for b in r.content:
    if b.type == "tool_use":
        print("tool_use:", b.name, b.input, "id =", b.id)
    elif b.type == "text":
        print("text:", b.text)

⌨️ Terminal

python first_call.py

🖥️ Output (sample run)

stop_reason: tool_use
text: Let me look up the latest CI result.
tool_use: get_test_result {'test_name': 'test_checkout_total'} id = toolu_01zz9Tx1c5uRBaJ8BMZSMJky

stop_reason is tool_use: Claude is waiting for you. The reply can also contain text before the tool call. Claude has not run anything; it only asked.

🪜 Step 4: Run the tool and return a tool_result

Append Claude’s whole reply as the assistant turn, then send one user message containing a tool_result for each tool_use, matched by tool_use_id:

📄 one_round.py

import json

import anthropic

from ci_tools import get_test_result
from tool_defs import TOOLS

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Why did test_checkout_total fail last night?"}]

r = client.messages.create(model="claude-opus-5-5", max_tokens=2000, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": r.content})

results = []
for b in r.content:
    if b.type == "tool_use":
        output = get_test_result(**b.input)
        results.append({"type": "tool_result", "tool_use_id": b.id, "content": json.dumps(output)})
messages.append({"role": "user", "content": results})

final = client.messages.create(model="claude-opus-5-5", max_tokens=2000, tools=TOOLS, messages=messages)
print(final.stop_reason, "->", final.content[0].text)

⌨️ Terminal

python one_round.py

🖥️ Output (sample run)

end_turn -> test_checkout_total failed in build 812: the order total was 100.00 instead of 90.00, so the 10% discount was not applied.
⚠️ Watch out: Three classic mistakes: (1) sending each tool_result in its own user message; (2) dropping the assistant turn that contains the tool_use; (3) sending a different tool_use_id. Each one either errors or confuses the model. All results for one turn go back together, in one user message.

🪜 Step 5: Loop until Claude finishes

Real tasks need several rounds. Loop on stop_reason, with a safety cap on iterations:

📄 loop.py

import json

import anthropic

from ci_tools import get_test_result
from tool_defs import TOOLS

client = anthropic.Anthropic()
REGISTRY = {"get_test_result": get_test_result}


def run_with_tools(question: str, max_rounds: int = 8) -> str:
    messages = [{"role": "user", "content": question}]
    for round_no in range(1, max_rounds + 1):
        r = client.messages.create(model="claude-opus-5-5", max_tokens=2000, tools=TOOLS, messages=messages)
        messages.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return f"(after {round_no} calls) " + "".join(b.text for b in r.content if b.type == "text")
        results = []
        for b in r.content:
            if b.type == "tool_use":
                try:
                    output = json.dumps(REGISTRY[b.name](**b.input))
                    results.append({"type": "tool_result", "tool_use_id": b.id, "content": output})
                except Exception as e:  # report failures to Claude instead of crashing
                    results.append({"type": "tool_result", "tool_use_id": b.id, "content": str(e), "is_error": True})
        messages.append({"role": "user", "content": results})
    return "stopped: too many tool rounds"


print(run_with_tools("Did test_login and test_checkout_total pass?"))

⌨️ Terminal

python loop.py

🖥️ Output (sample run)

(after 2 calls) test_login passed in build 812, but test_checkout_total failed with AssertionError: expected 90.00 got 100.00.
  • Claude asked for two tools in one turn (parallel tool use). The loop runs both and returns both results in a single message.
  • A tool that raises becomes a tool_result with "is_error": True. Claude reads the error and can recover (try another name, ask the user) instead of the app crashing.
  • The iteration cap is a safety backstop, not the stop condition. The stop condition is stop_reason.

🪜 Step 6: Control tool use with tool_choice

tool_choice Meaning
{"type": "auto"} (default) Claude decides whether to call a tool
{"type": "none"} Claude must not call tools in this turn
{"type": "any"} / {"type": "tool", "name": ...} Force a tool call. Rejected with a 400 on Claude Opus 5.5, Sonnet 5.5, Fable 5.1/5.2.

On current models, steer with the prompt (“Always look up the result with get_test_result before answering”) and use auto. If you were forcing a tool only to get JSON, use structured outputs instead (Lesson 22). Add "disable_parallel_tool_use": True to tool_choice if your tools must run one at a time.

🪜 Step 7: Let the Tool Runner drive the loop

The SDK’s Tool Runner (beta) builds the schema from a decorated function and runs the loop for you:

📄 runner.py

import anthropic
from anthropic import beta_tool

from ci_tools import get_test_result as lookup

client = anthropic.Anthropic()


@beta_tool
def get_test_result(test_name: str) -> str:
    """Get the latest CI result for one automated test.

    Args:
        test_name: Exact pytest function name, e.g. test_checkout_total.
    """
    return str(lookup(test_name))


runner = client.beta.messages.tool_runner(
    model="claude-opus-5-5",
    max_tokens=2000,
    tools=[get_test_result],
    messages=[{"role": "user", "content": "Why did test_checkout_total fail last night?"}],
)
final = runner.until_done()
print(final.stop_reason, "->", final.content[-1].text)

⌨️ Terminal

python runner.py

🖥️ Output (sample run)

end_turn -> test_checkout_total failed in build 812: the order total was 100.00 instead of 90.00, so the 10% discount was not applied.
  • The docstring becomes the description, and the Args: section describes each parameter.
  • In anthropic 2.13 the Tool Runner uses message threads (a beta feature) by default: the first request creates a thread, and later requests send only the new messages plus a previous_message_id, while the API keeps the earlier turns. This makes long tool loops lighter. Anthropic describes threads as best-effort, so keep your own log of the turns if you need a full trace or a replay.
  • Use the manual loop when you need full control (approvals before risky tools, custom logging, special pause_turn handling); use the Tool Runner for the rest.
🎯 Exam focus: Tool-loop defects are a favourite: stopping on “the reply contains text” instead of stop_reason, splitting results across messages, losing the assistant turn, crashing on tool errors instead of returning is_error, and forcing tool_choice on models that reject it.

🌍 Real-world example: Ravi’s CI assistant

Ravi’s first CI bot stopped whenever Claude wrote “Let me check that”, because his loop ended on any text. Users saw only that sentence. Switching the condition to stop_reason != "tool_use" fixed it, and returning is_error for unknown test names let Claude ask “Did you mean test_checkout_totals?” instead of crashing.

🧪 Practice Questions

Question 1. Claude replies with text “Checking now.” plus a tool_use block, and the app shows “Checking now.” to the user and stops. What is the loop defect?

  • A. max_tokens is too low
  • B. The loop ends when it sees text instead of continuing while stop_reason is tool_use
  • C. The tool schema is wrong
  • D. Parallel tool use is enabled
Show answer

Answer: B. Claude can write text and request a tool in the same turn. stop_reason, not the presence of text, decides whether more work is pending.

Question 2. Claude requests three tools in one turn. How should the results be returned?

  • A. Three separate user messages, one per result
  • B. One user message with three tool_result blocks, each with the matching tool_use_id
  • C. One tool_result containing all three outputs joined together
  • D. Only the first result; Claude will ask again
Show answer

Answer: B. All results for a turn go back together in a single user message, each linked to its tool_use_id.

Question 3. A tool raises an exception because the requested record does not exist. What should the loop do?

  • A. Return a tool_result with is_error: true and the error message, so Claude can recover
  • B. Crash and show a stack trace
  • C. Drop the tool_use and continue
  • D. Retry the same call 5 times
Show answer

Answer: A. Reporting the error lets Claude choose a recovery, such as asking for a correct identifier.

Question 4. Code sends tool_choice={“type”: “any”} to Claude Opus 5.5 and receives a 400. Which two alternatives are correct? (Choose 2.)

  • A. Use tool_choice auto and instruct the tool use in the prompt
  • B. Use tool_choice “required”
  • C. Use structured outputs if the forced call only existed to get JSON
  • D. Downgrade the SDK
Show answer

Answer: A and C. Forced tool choice is not supported on Opus 5.5. Steer with the prompt, or use structured outputs for JSON.

📝 Assignment

  1. Task 1: Add a second tool, get_flaky_history(test_name, days), that returns how many times a test failed recently, and ask “Is test_login flaky?”.
    ✅ Done when: the loop calls your new tool and answers from its result.
  2. Task 2: Write pytest tests for run_with_tools using unittest.mock to return a scripted tool_use reply and then a text reply.
    ✅ Done when: the test checks that the tool was called once with the right input.
  3. Stretch: Add an approval step: before running any tool whose name starts with create_ or delete_, ask the user y/n in the terminal and return an is_error result “rejected by user” on n.
    ✅ Done when: rejecting a call makes Claude explain that the action was not performed.

❓ Frequently Asked Questions

🤔 What is tool use in Claude?

A way for Claude to request actions from your code. You describe tools with JSON schemas; Claude returns tool_use blocks; your code runs them and returns tool_result blocks.

🤔 Does Claude execute my tools?

No. Client tools always run in your code. Claude only decides which tool to call and with which input. (Anthropic-hosted server tools, such as web search, run on Anthropic’s side; see Lesson 25.)

🤔 How do I return a tool error to Claude?

Send a tool_result with "is_error": true and a clear message. Claude can then retry differently or explain the problem.

🤔 What is the difference between the Tool Runner and the Agent SDK?

The Tool Runner (in the anthropic SDK) loops over tools you define. The Agent SDK is Claude Code’s full harness with built-in file, shell and web tools.

🏁 Summary

  • Describe tools with a name, a description written for Claude and an input schema.
  • Loop while stop_reason == "tool_use"; append the full assistant reply every time.
  • Return all tool_result blocks for a turn in one user message, matched by tool_use_id.
  • Report tool failures with is_error: true; cap iterations as a backstop only.
  • Use auto tool choice on current models, and the Tool Runner when you do not need custom control.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Tool Design: Descriptions, Response Shaping and Errors.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

Claude Structured Outputs in Python: JSON Schema and Pydantic

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D6 Structured Output and Defensive Parsing · D2 Messages API Mechanics

👋 In plain words: When code reads Claude’s answer, it needs a predictable shape, usually JSON. Structured outputs make Claude follow a schema you define. This lesson shows you how, step by step, and then how to protect your code from the cases a schema cannot cover: cut-off replies, refusals and wrong-but-valid values.

“Parse the JSON from the reply” is where many Claude integrations break: extra words around the JSON, a missing field, a truncated object. In this lesson you will use client.messages.parse() with a Pydantic model, send a raw JSON schema with output_config.format, make tool inputs strict, and build a defensive parsing layer that handles max_tokens, refusals, business-rule violations and free-text fallbacks.

📖 What You’ll Learn: You will be able to request schema-valid JSON from Claude with Pydantic or JSON Schema, use strict tool inputs, and parse defensively so malformed or unexpected output never reaches downstream code.

🔑 Key terms

  • Structured outputs: an API feature that constrains Claude’s reply to match a JSON schema (output_config.format).
  • JSON Schema: a standard way to describe the shape of JSON: types, required fields, allowed values.
  • Pydantic: a Python library that defines data models and validates data against them.
  • Strict tool use: strict: true on a tool definition, so Claude’s tool inputs always match the tool’s schema.
  • Defensive parsing: code that checks every assumption before trusting model output.

🪜 Step 1: Define the shape with Pydantic

Model the result you want. Literal limits a field to fixed values, and Field adds descriptions that also help Claude:

📄 models.py

from typing import Literal

from pydantic import BaseModel, Field


class TestCase(BaseModel):
    id: str = Field(description="TC-01, TC-02, ...")
    title: str
    priority: Literal["high", "medium", "low"]
    steps: list[str]
    expected: str


class TestSuite(BaseModel):
    feature: str
    cases: list[TestCase]

🪜 Step 2: Call messages.parse()

client.messages.parse() converts the Pydantic model to a JSON schema, sends it as the output format, and validates the reply into a model instance:

📄 parse_demo.py

import anthropic

from models import TestSuite

client = anthropic.Anthropic()

response = client.messages.parse(
    model="claude-opus-5-5",
    max_tokens=4000,
    messages=[{"role": "user", "content": "Write 2 test cases for: users can add a product to the cart from the product page."}],
    output_format=TestSuite,
)

suite = response.parsed_output  # a validated TestSuite instance
print(suite.feature)
for case in suite.cases:
    print(f"{case.id} [{case.priority}] {case.title} -> {case.expected}")

⌨️ Terminal

python parse_demo.py

🖥️ Output (sample run)

Add to cart from product page
TC-01 [high] Add an in-stock product -> Cart count increases by 1
TC-02 [medium] Add an out-of-stock product -> Button is disabled with an 'Out of stock' label
  • parsed_output is a real TestSuite object: suite.cases[0].priority is guaranteed to be one of the three allowed strings.
  • Behind the scenes the SDK sends output_config={"format": {"type": "json_schema", "schema": ...}} with additionalProperties: false.

🪜 Step 3: Use a raw JSON schema when you are not using Pydantic

The same feature works with a hand-written schema on messages.create(). Use output_config.format, not the old, deprecated output_format parameter:

📄 raw_schema.py

import json

import anthropic

client = anthropic.Anthropic()

schema = {
    "type": "object",
    "properties": {
        "severity": {"type": "string", "enum": ["critical", "major", "minor"]},
        "component": {"type": "string"},
        "needs_repro_steps": {"type": "boolean"},
    },
    "required": ["severity", "component", "needs_repro_steps"],
    "additionalProperties": False,
}

r = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=500,
    output_config={"format": {"type": "json_schema", "schema": schema}},
    messages=[{"role": "user", "content": "Bug: checkout fails sometimes. No other details."}],
)
data = json.loads(next(b.text for b in r.content if b.type == "text"))
print(data)

⌨️ Terminal

python raw_schema.py

🖥️ Output (sample run)

{'severity': 'major', 'component': 'checkout', 'needs_repro_steps': True}
💡 Tip: Structured outputs replace older tricks such as assistant prefill ({), which current models reject, and forced tool calls used only to get JSON, which tool_choice any/tool no longer allows on Claude Opus 5.5 and Sonnet 5.5.

🪜 Step 4: Make tool inputs strict

When Claude calls your tools, add "strict": True to the tool definition. The schema must set additionalProperties: false and list required fields. Claude’s tool_use.input then always matches the schema:

📄 strict_tool.py

CREATE_TICKET = {
    "name": "create_ticket",
    "description": "Create a Jira bug ticket for a failed test.",
    "strict": True,
    "input_schema": {
        "type": "object",
        "properties": {
            "summary": {"type": "string"},
            "priority": {"type": "string", "enum": ["P1", "P2", "P3"]},
            "test_name": {"type": "string"},
        },
        "required": ["summary", "priority", "test_name"],
        "additionalProperties": False,
    },
}

Module 6 uses tools like this in a full tool-use loop.

🪜 Step 5: Parse defensively

A schema guarantees shape. It cannot guarantee that the reply is complete, that Claude did not decline, or that the values make sense. Check these in order:

  1. stop_reason == "max_tokens": the JSON may be cut off. parse() then raises a Pydantic ValidationError (invalid JSON).
  2. stop_reason == "refusal": Claude declined; parsed_output is None.
  3. Business rules the schema cannot express: unique IDs, at least one high-priority case, steps not empty.

📄 safe_parse.py

import anthropic
from pydantic import ValidationError

from models import TestSuite

client = anthropic.Anthropic()


def generate_suite(feature: str, max_tokens: int = 4000) -> TestSuite:
    try:
        r = client.messages.parse(model="claude-opus-5-5", max_tokens=max_tokens, output_format=TestSuite,
                                  messages=[{"role": "user", "content": f"Write 2 test cases for: {feature}"}])
    except ValidationError as e:
        raise RuntimeError(f"reply was not valid JSON (often a max_tokens cut-off): {e.errors()[0]['type']}") from e
    if r.stop_reason == "refusal":
        raise RuntimeError("Claude declined this request")
    if r.stop_reason == "max_tokens":
        raise RuntimeError("reply hit max_tokens; raise the limit")
    suite = r.parsed_output
    ids = [c.id for c in suite.cases]
    if len(ids) != len(set(ids)):
        raise RuntimeError(f"duplicate test IDs: {ids}")
    if any(not c.steps for c in suite.cases):
        raise RuntimeError("a test case has no steps")
    return suite


for feature, limit in [("search by product name", 4000), ("checkout with coupons", 30)]:
    try:
        print("OK  ", feature, "->", [c.id for c in generate_suite(feature, limit).cases])
    except RuntimeError as e:
        print("FAIL", feature, "->", e)

⌨️ Terminal

python safe_parse.py

🖥️ Output (sample run)

FAIL search by product name -> duplicate test IDs: ['TC-01', 'TC-01']
FAIL checkout with coupons -> reply was not valid JSON (often a max_tokens cut-off): json_invalid

The first reply is valid JSON with a valid shape, yet it has duplicate IDs, which only a business-rule check catches. The second was cut off by a tiny max_tokens, and the error explains why.

🪜 Step 6: Handle free-text fallbacks

Sometimes you cannot use structured outputs: an older model, a feature that is incompatible with them (citations, Lesson 20), or a third-party tool that returns text. Then extract and validate explicitly, and fail closed:

📄 fallback_parse.py

import json
import re

from pydantic import ValidationError

from models import TestCase


def parse_case_from_text(text: str) -> TestCase | None:
    match = re.search(r"\{.*\}", text, re.S)  # first {...} block in the text
    if not match:
        return None
    try:
        return TestCase.model_validate(json.loads(match.group(0)))
    except (json.JSONDecodeError, ValidationError):
        return None


samples = [
    'Sure! Here it is: {"id": "TC-09", "title": "Logout", "priority": "low", "steps": ["Click Logout"], "expected": "Login page shown"} Hope this helps.',
    '{"id": "TC-10", "title": "Login", "priority": "urgent", "steps": [], "expected": "x"}',
    "I could not write a test case for that.",
]
for s in samples:
    case = parse_case_from_text(s)
    print("parsed:", case.id if case else None)

⌨️ Terminal

python fallback_parse.py

🖥️ Output

parsed: TC-09
parsed: None
parsed: None
  • The first sample has chatty text around valid JSON: extracted and validated.
  • The second has an invalid priority value: rejected by Pydantic.
  • The third has no JSON: None, and the caller decides what to do (retry, flag for a human). Never pass half-parsed data downstream.
🎯 Exam focus: The skill is “structured outputs with strict schema validation, response validation, and defensive parsing of free-text fallbacks”. Strong answers: use structured outputs or strict tools for shape; check stop_reason before trusting output; validate business rules in code; fail closed on fallbacks. Weak answers: regex on raw text without validation, or “ask Claude nicely to return JSON”.

🌍 Real-world example: Ravi’s importer

Ravi’s test-case importer crashed twice a week on “Expecting ‘,’ delimiter”. The cause was replies cut off at max_tokens on large features. He moved to messages.parse() with a TestSuite model, raised max_tokens with streaming for big suites, and added the duplicate-ID check after one generated suite overwrote existing cases in Jira.

🧪 Practice Questions

Question 1. A pipeline parses Claude’s JSON with json.loads and sometimes fails with “Unterminated string”. The replies show stop_reason “max_tokens”. What is the right fix?

  • A. Wrap json.loads in a retry loop
  • B. Check stop_reason before parsing and raise max_tokens (with streaming for large outputs)
  • C. Ask Claude to use shorter field names
  • D. Switch to a different JSON library
Show answer

Answer: B. The JSON is truncated because generation hit the output limit. Retrying the same request hits the same limit.

Question 2. Code moved to Claude Opus 5.5 used tool_choice={“type”: “tool”, “name”: “extract”} only to force JSON and now gets 400 errors. What should replace it?

  • A. Structured outputs with output_config.format (or messages.parse with a Pydantic model)
  • B. An assistant prefill starting with {
  • C. temperature=0
  • D. A larger model
Show answer

Answer: A. Forced tool choice is rejected on Opus 5.5 and prefill is not supported. Structured outputs are the direct replacement for getting JSON.

Question 3. Which two checks belong in a defensive parser even when structured outputs are used? (Choose 2.)

  • A. Business rules the schema cannot express, such as unique IDs
  • B. Removing additionalProperties from the schema
  • C. Handling stop_reason values such as refusal and max_tokens
  • D. Converting every field to a string
Show answer

Answer: A and C. Schemas constrain shape only. Completeness, refusals and cross-field rules must be checked in code.

Question 4. messages.parse returns a response where parsed_output is None. What is the most likely reason?

  • A. The Pydantic model has too many fields
  • B. Claude declined the request, so stop_reason is “refusal”
  • C. The SDK does not support Pydantic
  • D. The response was cached
Show answer

Answer: B. A refusal produces no output to parse. Check stop_reason and handle the refusal explicitly.

📝 Assignment

  1. Task 1: Define a Pydantic model for one output your team needs (a bug triage, a test case, a release note) and call messages.parse() with it.
    ✅ Done when: your code uses parsed_output with no manual JSON parsing.
  2. Task 2: Add two business-rule checks to generate_suite that matter to your team.
    ✅ Done when: a hand-made invalid suite fails each check with a clear message.
  3. Stretch: Write pytest tests for parse_case_from_text covering chatty text, invalid enum values, missing fields, nested braces and no JSON.
    ✅ Done when: every case returns either a valid TestCase or None, never an exception.

❓ Frequently Asked Questions

🤔 How do I get JSON output from Claude in Python?

Use client.messages.parse() with a Pydantic model, or messages.create() with output_config={"format": {"type": "json_schema", "schema": ...}}.

🤔 Is output_format still supported?

The top-level output_format parameter on messages.create() is deprecated; use output_config.format. In the Python SDK, messages.parse() takes an output_format= argument for your Pydantic model and handles this for you.

🤔 What does strict: true do on a tool?

It guarantees that Claude’s input for that tool matches the tool’s JSON schema exactly. The schema needs additionalProperties: false and required.

🤔 Do I still need validation if I use structured outputs?

Yes. Check stop_reason, and validate business rules that a schema cannot express.

🏁 Summary

  • Define outputs as Pydantic models and use messages.parse(); read parsed_output.
  • Without Pydantic, use output_config.format with a JSON schema; never prefill.
  • Use strict: true for schema-valid tool inputs.
  • Check stop_reason (max_tokens, refusal) and business rules before trusting output.
  • For free text, extract, validate and fail closed.
📝 Test yourself: D6 Prompt and Context Engineering practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Tool Use in Python: Schemas and the Tool-Use Loop.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.

RAG vs Long Context with Claude: When to Retrieve

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D6 Grounding and Source Citation · D5 Cost Diagnosis and Optimization

👋 In plain words: You can give Claude your documents in two ways: send all of them with every question, or search them first and send only the relevant parts. The first is simple; the second scales. This lesson helps you pick the right one with a few concrete numbers, and builds a small search-then-answer pipeline you can run.

With 1M-token context windows, “just send everything” works for more projects than it used to, and it is often the right answer. But not always: big or fast-changing corpora, tight budgets and latency limits still call for retrieval-augmented generation (RAG). In this lesson you will size a corpus, compare the cost of full context with and without caching against retrieval, build a simple keyword retriever in plain Python, and send the top passages to Claude with citations.

📖 What You’ll Learn: You will be able to choose between full-document context and retrieval based on corpus size, cost, caching and freshness, and implement a basic retrieve-then-answer pipeline with citations.

🔑 Key terms

  • Corpus: the whole collection of documents your app answers from.
  • RAG (retrieval-augmented generation): search the corpus first, then send only the most relevant passages to the model.
  • Chunk: a small passage of a document, the unit you search and send.
  • Freshness: how often the corpus changes, and how quickly answers must reflect the change.

🪜 Step 1: Size your corpus

Count tokens, not pages (Lesson 5). Then compare with the context window and your budget:

Corpus Tokens (approx.) Fits in a 1M window?
One product’s test plan and runbook 30K Easily
All QA documentation of a team 400K Yes, but every question pays for 400K input tokens
Five years of bug reports 40M No

🪜 Step 2: Compare the costs

Full context means paying for the whole corpus on every question. Prompt caching cuts the repeated part to a fraction of the price (Lesson 43); retrieval sends only a few thousand tokens. This calculator uses Opus 5.5 list prices; cache reads on Opus 5.5 are listed at $0.20 per million tokens:

📄 cost_compare.py

INPUT, CACHE_READ = 4.00, 0.20   # Claude Opus 5.5, $ per million input tokens
questions_per_day = 2_000


def daily(tokens_per_question: int, price: float) -> float:
    return questions_per_day * tokens_per_question / 1_000_000 * price


corpus = 400_000
print(f"full context, no cache : ${daily(corpus, INPUT):>9,.2f} per day")
print(f"full context, cached   : ${daily(corpus, CACHE_READ):>9,.2f} per day (plus cache writes)")
print(f"RAG, 6K tokens/question: ${daily(6_000, INPUT):>9,.2f} per day (plus retrieval infrastructure)")

⌨️ Terminal

python cost_compare.py

🖥️ Output

full context, no cache : $ 3,200.00 per day
full context, cached   : $   160.00 per day (plus cache writes)
RAG, 6K tokens/question: $    48.00 per day (plus retrieval infrastructure)
  • Caching makes full context far cheaper when the corpus is stable and questions are frequent, because the cached prefix is reused.
  • Retrieval is cheapest per question and has no size ceiling, but you build and maintain the search.
  • Output tokens are the same in all three designs, so they are left out here.

🪜 Step 3: Decide with four questions

  1. Does the corpus fit comfortably (well under the context window, with room for history and output)? If not → RAG.
  2. How often does it change? If documents change many times a day, a cached prefix is invalidated often → lean to RAG (re-index only changed documents).
  3. How many questions and what latency? Huge prompts take longer to process; frequent questions on a stable corpus → full context + caching.
  4. Do answers need the whole corpus at once (compare every requirement with every test)? → full context. Questions about one fact → RAG is enough.
🎯 Exam focus: The skill text says you decide “based on corpus size, cost, and freshness, whether to supply the full document set in context or retrieve only the relevant passages”. Expect scenarios with numbers. A small, stable corpus queried often → full context with caching. A large or fast-changing corpus → retrieval.

🪜 Step 4: Build a simple retriever

Production RAG often uses embeddings and a vector database, but the idea fits in a few lines. This retriever scores chunks by keyword overlap with the question. It runs locally:

📄 retriever.py

import math
import re
from collections import Counter

DOCS = {
    "runbook": "Staging deploys run every weekday at 14:00 UTC. If the payments sandbox is down, mark payment tests as blocked, not failed.",
    "flaky-policy": "Flaky tests are quarantined after 3 failures in 7 days. A quarantined test must be fixed within 10 working days.",
    "release": "Release candidates need a full regression run with zero critical failures and sign-off from the QA lead.",
    "perf": "Performance tests run weekly on Sunday against the perf environment with 500 virtual users.",
}


def words(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", text.lower())


def chunks(docs: dict, size: int = 18) -> list[tuple[str, str]]:
    out = []
    for name, text in docs.items():
        w = text.split()
        out += [(name, " ".join(w[i:i + size])) for i in range(0, len(w), size)]
    return out


CHUNKS = chunks(DOCS)
DF = Counter(t for _, c in CHUNKS for t in set(words(c)))


def search(question: str, k: int = 2) -> list[tuple[float, str, str]]:
    q = set(words(question))
    scored = []
    for name, chunk in CHUNKS:
        score = sum(math.log(len(CHUNKS) / DF[t]) for t in q & set(words(chunk)))
        scored.append((round(score, 2), name, chunk))
    return sorted(scored, reverse=True)[:k]


if __name__ == "__main__":
    for score, name, chunk in search("When is a flaky test quarantined?"):
        print(f"{score:>5}  [{name}] {chunk}")

⌨️ Terminal

python retriever.py

🖥️ Output

 6.47  [flaky-policy] Flaky tests are quarantined after 3 failures in 7 days. A quarantined test must be fixed within 10
 1.79  [runbook] Staging deploys run every weekday at 14:00 UTC. If the payments sandbox is down, mark payment tests as
  • Rare words (like “quarantined”) count more than common ones, a simple version of the idea behind BM25 and TF-IDF.
  • Keyword search misses synonyms (“unstable test” vs “flaky test”). That is where embedding search helps; many teams combine both.

🪜 Step 5: Send the top passages with citations

Feed only the retrieved chunks to Claude as cited documents, with the not-found rule from the previous lesson:

📄 rag_answer.py

import anthropic

from retriever import search

client = anthropic.Anthropic()

question = "When is a flaky test quarantined?"
hits = search(question)
docs = [{"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": chunk},
         "title": name, "citations": {"enabled": True}} for _, name, chunk in hits]

r = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=500,
    system="Answer only from the documents. If they do not contain the answer, reply exactly: NOT_FOUND",
    messages=[{"role": "user", "content": docs + [{"type": "text", "text": question}]}],
)
print("retrieved:", [name for _, name, _ in hits])
for b in r.content:
    if b.type == "text":
        print("answer:", b.text, "| sources:", [c.document_title for c in (b.citations or [])])

⌨️ Terminal

python rag_answer.py

🖥️ Output (sample run)

retrieved: ['flaky-policy', 'runbook']
answer: After 3 failures in 7 days. | sources: ['flaky-policy']

🪜 Step 6: Test the retriever like any other component

RAG fails in two places: retrieval (the right chunk was not found) and generation (the right chunk was found but the answer is wrong). Test them separately:

📄 test_retriever.py

from retriever import search


def test_flaky_question_finds_policy():
    assert search("When is a flaky test quarantined?")[0][1] == "flaky-policy"


def test_release_question_finds_release_doc():
    assert search("What does a release candidate need?")[0][1] == "release"

⌨️ Terminal

pytest -q -p no:cacheprovider test_retriever.py

🖥️ Output

..                                                                       [100%]
2 passed in 0.42s

When an answer is wrong, first check whether the right passage was retrieved. If not, fix retrieval (chunk size, synonyms, more results); if it was, fix the prompt.

🌍 Real-world example: Ravi chooses per corpus

Ravi’s team has a 25K-token QA handbook and 2 million tokens of historical bug reports. For the handbook bot he sends the whole handbook with a cache breakpoint: answers can use any section and the cost is small. For “has this bug happened before?” he built retrieval over the bug reports, re-indexed nightly, and sends the top 8 matches with citations.

🧪 Practice Questions

Question 1. A 40K-token QA handbook changes once a month and is queried 5,000 times a day. What is the most sensible design?

  • A. Send the full handbook with a prompt-cache breakpoint after it
  • B. Build a vector database and retrieve 3 chunks per question
  • C. Fine-tune a model on the handbook
  • D. Send the handbook without caching
Show answer

Answer: A. The corpus is small and stable and questions are frequent, so caching the full handbook is simple, accurate and cheap.

Question 2. A support knowledge base of 15 million tokens changes hourly. Which approach fits?

  • A. Full context with caching
  • B. Retrieval of relevant passages, re-indexing changed documents
  • C. Sending everything in a Message Batch
  • D. Splitting it across 15 requests per question
Show answer

Answer: B. It does not fit in the context window and changes too often for a stable cached prefix.

Question 3. A RAG answer is wrong. Logs show the correct passage was not among the retrieved chunks. Where should you fix it?

  • A. In retrieval: chunking, query terms, synonyms or the number of results
  • B. In the generation prompt only
  • C. By raising max_tokens
  • D. By switching to a larger model
Show answer

Answer: A. If the right passage never reaches Claude, no prompt change can produce a grounded answer.

Question 4. Which two factors does the exam name for choosing full context versus retrieval? (Choose 2.)

  • A. Corpus size
  • B. The programming language of the app
  • C. Freshness (how often the documents change)
  • D. The colour scheme of the UI
Show answer

Answer: A and C. The skill names corpus size, cost and freshness.

📝 Assignment

  1. Task 1: Count the tokens of your team’s main QA documents and run cost_compare.py with your own numbers.
    ✅ Done when: you can say which design is cheaper for your question volume.
  2. Task 2: Add 10 of your own document chunks to DOCS and write 5 retriever tests like test_retriever.py.
    ✅ Done when: all tests pass, or you have changed chunking until they do.
  3. Stretch: Make search also match simple synonyms (for example “unstable” → “flaky”) with a small dictionary, and add a test for it.
    ✅ Done when: “When is an unstable test quarantined?” finds the flaky policy.

❓ Frequently Asked Questions

🤔 Do I still need RAG with a 1M-token context window?

Often not, for small, stable corpora. You still need retrieval when the corpus is too large, changes very often, or full-context cost and latency are too high.

🤔 Is RAG cheaper than long context?

Per question, usually yes. But full context with prompt caching can be close in cost and simpler to build when the corpus is stable and questions are frequent.

🤔 How do I test a RAG system?

Test retrieval (does the right passage come back?) and generation (is the answer grounded and correct?) separately, with a golden set of questions.

🤔 What is chunking?

Splitting documents into small passages for search. Chunk size affects whether the right passage is found and how much context it carries.

🏁 Summary

  • Size the corpus in tokens and decide on size, cost and freshness.
  • Small, stable, frequently queried corpus → full context with caching.
  • Large or fast-changing corpus → retrieval of the relevant passages.
  • Even simple keyword retrieval works for small sets; combine with embeddings at scale.
  • Test retrieval and generation separately, and cite sources in the answer.
📝 Test yourself: D6 Prompt and Context Engineering practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Structured Outputs in Python: JSON Schema and Pydantic.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.