skip to content

How do you give a Claude Agent SDK agent an in-process custom tool with tool() and createSdkMcpServer, and which name do you pre-approve?

level: middleimportance: should knowfreq 8%

answer

  1. an MCP server without a process
  2. name, description, schema, handler
  3. the mcpServers key names the server
  4. mcp__ prefix, double underscores
  5. errors become results, not crashes

basics

~10 s

Define the tool with tool() (Python @tool) as name, description, schema and async handler, wrap it with createSdkMcpServer, pass it under a key in mcpServers, and pre-approve mcp__<key>__<tool> in allowedTools.

solid answer

~40 s

In TypeScript, `tool()` takes a name, a description Claude reads, a Zod input schema and an async handler; Python's `@tool` decorator takes the same parts with a dict or JSON Schema. The handler returns `{ content: [...] }`, optionally with `isError: true`. You wrap one or more tools with `createSdkMcpServer` (`create_sdk_mcp_server`), which runs inside your application rather than as a separate process, and pass it to `query()` in `mcpServers`. The **key** you use there becomes the server segment of the tool's full name, `mcp__{server}__{tool}`, so a server under `prs` with `get_pr_diff` is pre-approved as `mcp__prs__get_pr_diff` (or `mcp__prs__*`). A handler that throws does not end the run: the error becomes a tool result and the loop continues. Annotations such as `readOnlyHint` are hints for scheduling, not enforcement.

code

typescript · 25 lines
typescript
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const getPrDiff = tool(
  "get_pr_diff",
  "Return the unified diff of a pull request from the internal git host",
  { prNumber: z.number().int().describe("Pull request number") },
  async (args) => {
    const res = await fetch(`https://git.example.com/api/prs/${args.prNumber}/diff`);
    if (!res.ok) {
      return { content: [{ type: "text", text: `Diff fetch failed: HTTP ${res.status}` }], isError: true };
    }
    return { content: [{ type: "text", text: await res.text() }] };
  },
  { annotations: { readOnlyHint: true } }
);

const prs = createSdkMcpServer({ name: "prs", version: "1.0.0", tools: [getPrDiff] });

for await (const message of query({
  prompt: "Summarise pull request 482 as release-note bullets",
  options: { mcpServers: { prs }, allowedTools: ["mcp__prs__get_pr_diff"] },
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

go deeper

for a junior

Recall the four parts of a tool, that createSdkMcpServer wraps tools into an in-process server, and that the full name is mcp__ plus the server key plus the tool name.

for a middle

Explain how the mcpServers key forms the tool name, why allowedTools needs that full name, how tool search defers schemas, and what a thrown error turns into.

for a senior

Design a restricted agent with tools: [] and pre-approved custom tools, compose isError messages Claude can act on, and keep annotations honest because nothing enforces them.

for a principal

Decide which capabilities belong in in-process tools sharing the service's credentials and which belong behind a separately deployed MCP server with its own permissions and lifecycle.

## In-process tools, briefly The Agent SDK lets your application hand Claude its own functions as **custom tools**. It does this through the **Model Context Protocol (MCP)**, the same mechanism Claude Code uses for external tool servers, but with an **in-process SDK server**: the server object lives in your Node or Python process, so your handler can use your database pool, your HTTP client and your configuration directly. There is nothing to launch, no port and no separate binary. ## The four parts of a tool A tool passed to `tool()` (TypeScript) or `@tool` (Python) has: 1. **Name:** the identifier Claude calls, such as `get_pr_diff`. 2. **Description:** what the tool does; Claude reads it to decide when to call the tool. 3. **Input schema:** in TypeScript always a Zod schema, which also types the handler's `args`; in Python a dict such as `{"pr_number": int}` that the SDK converts to JSON Schema, or a full JSON Schema dict when you need enums, ranges or optional fields. 4. **Handler:** an async function that receives validated arguments and returns an object with `content`, an array of blocks of type `text`, `image`, `audio`, `resource` or `resource_link`, plus optional `isError` and `structuredContent`. A fifth argument in TypeScript (the `annotations` keyword in Python) carries **tool annotations**. `readOnlyHint: true` lets Claude call the tool in parallel with other read-only tools; `destructiveHint`, `idempotentHint` and `openWorldHint` are informational. None of them is enforced: a tool marked read-only can still write if its handler does. ## Registering and naming `createSdkMcpServer({ name, version, tools })` (Python `create_sdk_mcp_server(name=..., version=..., tools=[...])`) wraps the tools. You pass the server to `query()` in `mcpServers`, and the **key in that object** becomes the server segment of each tool's fully qualified name: | Piece | Example | |---|---| | `mcpServers` key | `prs` | | Tool name | `get_pr_diff` | | Name Claude and the permission system see | `mcp__prs__get_pr_diff` | | One allow entry for every tool on that server | `mcp__prs__*` | Listing that name in `allowedTools` lets the tool run **without a permission prompt**; without it, calls go through the normal permission flow. Allow rules accept a glob only after a literal `mcp__<server>__` prefix: an unanchored `mcp__*` or `*` in `allowedTools` is ignored with a startup warning. The same `mcp__<server>__<tool>` form is what a hook `matcher` tests. ## Availability is a separate layer - The `tools` option controls **built-in** tools only: `tools: []` removes every built-in and leaves your MCP tools, which is how you build an agent that can only call your functions. - A bare name in `disallowedTools` removes that tool from Claude's context entirely. - **Tool search** is on by default and defers SDK MCP tools: Claude sees each name in a compact list and loads the full schema when needed. In TypeScript, `alwaysLoad: true` on `tool()` or `createSdkMcpServer()` keeps a schema in the initial prompt. ## Errors do not stop the loop The in-process server catches an uncaught exception and returns it as an **error result** carrying the raw message; Claude sees it and the loop continues. Catching the error yourself and returning `isError: true` (Python `"is_error": True`) lets you write a message Claude can act on, such as which request failed and what to try instead. Either way Claude may retry, try another tool or explain the failure. ## Language differences worth knowing - Python's dict schema treats every key as required; for an optional parameter, leave it out of the schema, mention it in the description and read it with `args.get()`. TypeScript uses `.optional()` on the Zod field. - The Python `@tool` decorator forwards only `content` and `is_error`; to return `structuredContent` from Python, run a standalone MCP server instead. - Designing the schema itself, which parameters to require and how to word the description, is general tool-design practice rather than anything specific to this SDK. ## Common mistakes - Pre-approving the bare tool name instead of the `mcp__` form, so every call still prompts. - Expecting `readOnlyHint` to sandbox the handler. - Starting a separate MCP server process for code that could run in-process. - Letting raw stack traces reach Claude when a composed `isError` message would steer it better.

  • How do you build an SDK agent that can call only your custom tools and none of Claude Code's built-ins?
    Pass `tools: []`, which removes every built-in tool from Claude's context while leaving MCP tools untouched, register your server in `mcpServers`, and pre-approve its tools in `allowedTools`. If the agent should still ask clarifying questions, include `AskUserQuestion` in `tools` and handle it in `canUseTool`.
  • Your handler calls a flaky API. Should it throw or return isError?
    Either keeps the loop running, because the in-process server turns an uncaught exception into an error result. Returning `isError: true` with a composed message is better when the raw exception would not tell Claude what went wrong or what to try next, for example naming the HTTP status and suggesting a retry later.

  • createSdkMcpServer starts a separate server process you must launch and supervise.
  • Putting the bare name get_pr_diff in allowedTools pre-approves the custom tool.
  • readOnlyHint stops a handler from writing anything.
  • A handler that throws aborts the whole query.
  • tools: [] removes your custom MCP tools along with the built-ins.