Skip to content
AgenticAIWiki
  1. Learn
  2. Part 8
  3. 42. The agent loop and agent SDKs
  4. 42.2

Lesson 42.2 · 2 of 4 · 7 min read · Reviewed 24 Nov 2026

Building with an agent SDK

By the end, you can

  • Run an agent with the Claude Agent SDK's query() function.
  • Restrict an agent's tools with allowedTools and read its final result.

Writing the loop yourself is a great way to learn it. In production, the Claude Agent SDKClaude Agent SDK: Anthropic’s library for building agents on the same loop that powers Claude Code, with tools, hooks, subagents and MCP. gives you the same loop that powers Claude Code: built-in toolsBuilt-in tools: Tools provided by the platform rather than by you, such as web search, code execution or a text editor tool., permission checks, context compactionCompaction: Summarising older conversation history so a long session fits in the context window while keeping what matters. and hooksHook: Code that runs automatically at a lifecycle event, such as before or after a tool call, to check, block or log it..

A first agent

import { query } from '@anthropic-ai/claude-agent-sdk';

for await (const message of query({
  prompt: 'Find where the retry delay is set and explain it.',
  options: { allowedTools: ['Read', 'Grep', 'Glob'], maxTurns: 8 },
})) {
  if (message.type === 'result') {
    console.log(message.subtype, message.num_turns, message.total_cost_usd);
    if (message.subtype === 'success') console.log(message.result);
  }
}

query() streamsStreaming: Receiving a response as a series of server-sent events while it is generated, instead of waiting for the whole reply. messages as the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. works: a system message with the session id, assistant messages with tool calls, and a final result message. Check its subtype: success, or an error such as hitting the turn limit.

Your own tools

Define tools with a name, description and zod schema, bundle them into an in-process MCPModel Context Protocol (MCP): An open protocol that standardises how AI applications connect to tools, data and prompts through servers. server with createSdkMcpServer, and add them to allowedTools by name (mcp__server__tool). The Playground’s Support agent project does exactly this.

Start narrow

Give the agent the fewest tools that let it do the job. Read-only tools first. Add writes when you have hooks and permission rulesPermission rule: An allow, ask or deny rule that controls which tools, commands or paths a coding agent may use. in place (chapters 44 and 45).

Key points

  • The Agent SDK runs the agent loop for you: tool calls, results, context management and retries.
  • query() streams messages; the final one has type "result" with the answer, turn count and cost.
  • allowedTools limits which tools the agent may use; start narrow and widen only when needed.
Hands-on labRuns in the Playground

Run a first agent with the SDK

Use the Playground's simulated Claude Agent SDK to run query() with one custom tool and a narrow allowed tools list, and read the message stream.

You will have: A script that prints each message type from the stream, the tools the agent was given, and how the run ended.

Steps

  1. Define a lookup_setting tool with @tool and bundle it into an in-process MCP server with create_sdk_mcp_server.
  2. Set allowed_tools to just mcp__config__lookup_setting and max_turns to 4.
  3. Iterate over query() and print the type of each message as it arrives.
  4. From the first SystemMessage, print the tools list in its data.
  5. From the final ResultMessage, print its subtype and number of turns, and the answer if the subtype is success.

Done when

  • The stream starts with a SystemMessage and ends with a ResultMessage.
  • The tools list shows only mcp__config__lookup_setting.
  • The script checks the result's subtype before printing an answer.

Open in the Playground No API key needed.

Starter code (Python)
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, tool, create_sdk_mcp_server

@tool("lookup_setting", "Look up a configuration value by name", {"name": str})
async def lookup_setting(args):
    values = {"retry_delay": "2.0 seconds", "timeout": "30 seconds"}
    return {"content": [{"type": "text", "text": values.get(args["name"], "not set")}]}

server = create_sdk_mcp_server("config", tools=[lookup_setting])

async def main():
    options = ClaudeAgentOptions(
        mcp_servers={"config": server},
        allowed_tools=[],      # TODO: allow only the lookup tool, by its mcp__server__tool name
        max_turns=4,
    )
    async for message in query(prompt="What is the retry delay set to?", options=options):
        # TODO: print type(message).__name__; read tools from the SystemMessage and subtype from the ResultMessage
        pass

asyncio.run(main())
Show a solution
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, tool, create_sdk_mcp_server, SystemMessage, ResultMessage

@tool("lookup_setting", "Look up a configuration value by name", {"name": str})
async def lookup_setting(args):
    values = {"retry_delay": "2.0 seconds", "timeout": "30 seconds"}
    return {"content": [{"type": "text", "text": values.get(args["name"], "not set")}]}

server = create_sdk_mcp_server("config", tools=[lookup_setting])

async def main():
    options = ClaudeAgentOptions(
        mcp_servers={"config": server},
        allowed_tools=["mcp__config__lookup_setting"],
        max_turns=4,
    )
    kinds = []
    async for message in query(prompt="What is the retry delay set to?", options=options):
        kinds.append(type(message).__name__)
        if isinstance(message, SystemMessage):
            print("tools given:", message.data["tools"])
        if isinstance(message, ResultMessage):
            print("ended with a result message; turns:", message.num_turns)
            if message.subtype == "success":
                print("answer received")
            else:
                print("no answer:", message.subtype)
    print("first:", kinds[0], "last:", kinds[-1])

asyncio.run(main())

Do it Build an Agent SDK agent in the Playground in the Playground. No API key needed.

Quick checkYou want an agent that can read and search files but never edit them. What do you set?
How sure are you?
Pick an answer and how sure you are