Chapter 3

The Agent SDK

Deep dive into the core concepts and architecture of the Claude Agent SDK.

Functions

Core functions for building agents with the SDK.

query()

The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive.

query-signature.ts
function query({
  prompt,
  options
}: {{
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query

Parameters

ParameterTypeDescription
promptstring | AsyncIterable<SDKUserMessage>The input prompt as a string or async iterable for streaming mode
optionsOptionsOptional configuration object (see Options type below)

Returns

Returns a Query object that extends AsyncGenerator<SDKMessage, void> with additional methods.

tool()

Creates a type-safe MCP tool definition for use with SDK MCP servers.

tool-signature.ts
function tool<Schema extends ZodRawShape>(
  name: string,
  description: string,
  inputSchema: Schema,
  handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>
): SdkMcpToolDefinition<Schema>

Parameters

ParameterTypeDescription
namestringThe name of the tool
descriptionstringA description of what the tool does
inputSchemaSchema extends ZodRawShapeZod schema defining the tool's input parameters
handler(args, extra) => Promise<CallToolResult>Async function that executes the tool logic

createSdkMcpServer()

Creates an MCP server instance that runs in the same process as your application.

createSdkMcpServer-signature.ts
function createSdkMcpServer(options: {
  name: string;
  version?: string;
  tools?: Array<SdkMcpToolDefinition<any>>;
}): McpSdkServerConfigWithInstance

Parameters

ParameterTypeDescription
options.namestringThe name of the MCP server
options.versionstringOptional version string
options.toolsArray<SdkMcpToolDefinition>Array of tool definitions created with tool()

Example Usage

mcp-server-example.ts
import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

// Define a custom tool
const weatherTool = tool(
  "get_weather",
  "Get current weather for a city",
  { city: z.string() },
  async ({ city }) => ({ content: [{ type: "text", text: `72°F in ${city}` }] })
);

// Create an in-process MCP server
const server = createSdkMcpServer({
  name: "weather-server",
  tools: [weatherTool]
});

// Use with query()
for await (const msg of query({
  prompt: "What's the weather in Tokyo?",
  options: { mcpServers: { weather: server } }
})) {console.log(msg); }