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;
}): QueryParameters
| Parameter | Type | Description |
|---|---|---|
prompt | string | AsyncIterable<SDKUserMessage> | The input prompt as a string or async iterable for streaming mode |
options | Options | Optional 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
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the tool |
description | string | A description of what the tool does |
inputSchema | Schema extends ZodRawShape | Zod 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>>;
}): McpSdkServerConfigWithInstanceParameters
| Parameter | Type | Description |
|---|---|---|
options.name | string | The name of the MCP server |
options.version | string | Optional version string |
options.tools | Array<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); }