Skip to main content
guidesSource-backed

Building In-Process MCP Tools with the Claude Agent SDK

A practical walkthrough of defining in-process custom tools for the Claude Agent SDK with createSdkMcpServer and the tool helper, wiring them into query via mcpServers, allowing them, error handling, and returning images or structured data.

by JPette1783·added 2026-06-05·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/agent-sdk/custom-tools, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/building-in-process-mcp-tools-with-the-claude-agent-sdk.mdx
Safety notes
Custom tool handlers run your code in-process whenever Claude calls them; validate inputs and gate destructive actions inside the handler., List each tool in allowedTools (mcp__server__tool) so it runs without a prompt only when you intend; otherwise it goes through the permission flow., Return isError instead of throwing so a failed tool keeps the agent loop alive rather than crashing the whole query., Tool annotations like readOnlyHint are metadata, not enforcement; keep them accurate to what the handler actually does.
Privacy notes
In-process tools run inside your application, so data they touch stays in your process unless the handler sends it elsewhere., Tool descriptions, inputs, and results are sent to the model provider as part of the conversation; avoid placing secrets in them., Every tool definition consumes context on each turn; for large tool sets, load them on demand rather than sending all schemas.
Author
JPette1783
Submitted by
JPette1783
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup. Have accounts and credentials ready first.

0/3 ready
Account & credentials1Install & runtime2

Safety & privacy surface

Safety & privacy surface

4 safety and 3 privacy notes across 4 risk areas. Review closely: credentials & tokens, permissions & scopes.

4 areas
  • SafetyExecution & processesCustom tool handlers run your code in-process whenever Claude calls them; validate inputs and gate destructive actions inside the handler.
  • SafetyPermissions & scopesList each tool in allowedTools (mcp__server__tool) so it runs without a prompt only when you intend; otherwise it goes through the permission flow.
  • SafetyGeneralReturn isError instead of throwing so a failed tool keeps the agent loop alive rather than crashing the whole query.
  • SafetyGeneralTool annotations like readOnlyHint are metadata, not enforcement; keep them accurate to what the handler actually does.
  • PrivacyExecution & processesIn-process tools run inside your application, so data they touch stays in your process unless the handler sends it elsewhere.
  • PrivacyCredentials & tokensTool descriptions, inputs, and results are sent to the model provider as part of the conversation; avoid placing secrets in them.
  • PrivacyGeneralEvery tool definition consumes context on each turn; for large tool sets, load them on demand rather than sending all schemas.

Safety notes

  • Custom tool handlers run your code in-process whenever Claude calls them; validate inputs and gate destructive actions inside the handler.
  • List each tool in allowedTools (mcp__server__tool) so it runs without a prompt only when you intend; otherwise it goes through the permission flow.
  • Return isError instead of throwing so a failed tool keeps the agent loop alive rather than crashing the whole query.
  • Tool annotations like readOnlyHint are metadata, not enforcement; keep them accurate to what the handler actually does.

Privacy notes

  • In-process tools run inside your application, so data they touch stays in your process unless the handler sends it elsewhere.
  • Tool descriptions, inputs, and results are sent to the model provider as part of the conversation; avoid placing secrets in them.
  • Every tool definition consumes context on each turn; for large tool sets, load them on demand rather than sending all schemas.

Prerequisites

  • The Claude Agent SDK installed for Python (claude-agent-sdk) or TypeScript (@anthropic-ai/claude-agent-sdk).
  • For TypeScript, Zod for input schemas; for Python, a dict or JSON Schema per tool.
  • An Anthropic API key or other configured provider credentials for the SDK.

Schema details

Install type
copy
Troubleshooting
No
Full copyable content
## Overview

Custom tools let Claude call your own functions during an Agent SDK session.
Using the SDK's in-process MCP server, you define tools with an input schema and
a handler, bundle them into a server that runs inside your application (not a
separate process), and pass them to `query`.

## Define a tool

A tool has a name, description, input schema, and async handler. Use the `tool()`
helper (TypeScript, Zod schema) or the `@tool` decorator (Python, dict or JSON
Schema), then wrap tools in a server.

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

const getTemperature = tool(
  "get_temperature",
  "Get the current temperature at a location",
  { latitude: z.number(), longitude: z.number() },
  async (args) => ({ content: [{ type: "text", text: `...` }] }),
);

const weatherServer = createSdkMcpServer({
  name: "weather",
  version: "1.0.0",
  tools: [getTemperature],
});
```

Python uses `@tool(...)` and `create_sdk_mcp_server(...)` with the same shape.

## Register and allow the tool

Pass the server via `mcpServers`. The key becomes the `{server_name}` segment of
the fully qualified name `mcp__{server_name}__{tool_name}`; list that in
`allowedTools` so it runs without a prompt.

```typescript
for await (const message of query({
  prompt: "What's the temperature in San Francisco?",
  options: {
    mcpServers: { weather: weatherServer },
    allowedTools: ["mcp__weather__get_temperature"],
  },
})) { /* ... */ }
```

Use the wildcard `mcp__weather__*` to allow every tool a server exposes.

## Handle errors

Return `isError: true` (TS) / `"is_error": True` (Python) from the handler when a
call fails. The agent loop continues and Claude can retry or explain. An uncaught
exception stops the loop and fails the `query` call.

## Return images and structured data

A handler's `content` array accepts `text`, `image` (base64, no data URI prefix),
and `resource` blocks. Set `structuredContent` to return machine-readable JSON
alongside the content. (In Python, `structuredContent` requires a standalone MCP
server rather than the in-process `@tool` decorator.)

## Annotations and scaling

Pass annotations like `readOnlyHint: true` so Claude can batch parallel-safe
calls. Every tool definition consumes context each turn; for dozens of tools, use
tool search to load them on demand.

## Source

- Give Claude custom tools: https://code.claude.com/docs/en/agent-sdk/custom-tools
- Connect MCP servers: https://code.claude.com/docs/en/agent-sdk/mcp

About this resource

Overview

Custom tools let Claude call your own functions during an Agent SDK session. Using the SDK's in-process MCP server, you define tools with an input schema and a handler, bundle them into a server that runs inside your application (not a separate process), and pass them to query.

Define a tool

A tool has a name, description, input schema, and async handler. Use the tool() helper (TypeScript, Zod schema) or the @tool decorator (Python, dict or JSON Schema), then wrap tools in a server.

import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const getTemperature = tool(
  "get_temperature",
  "Get the current temperature at a location",
  { latitude: z.number(), longitude: z.number() },
  async (args) => ({ content: [{ type: "text", text: `...` }] }),
);

const weatherServer = createSdkMcpServer({
  name: "weather",
  version: "1.0.0",
  tools: [getTemperature],
});

Python uses @tool(...) and create_sdk_mcp_server(...) with the same shape.

Register and allow the tool

Pass the server via mcpServers. The key becomes the {server_name} segment of the fully qualified name mcp__{server_name}__{tool_name}; list that in allowedTools so it runs without a prompt.

for await (const message of query({
  prompt: "What's the temperature in San Francisco?",
  options: {
    mcpServers: { weather: weatherServer },
    allowedTools: ["mcp__weather__get_temperature"],
  },
})) { /* ... */ }

Use the wildcard mcp__weather__* to allow every tool a server exposes.

Handle errors

Return isError: true (TS) / "is_error": True (Python) from the handler when a call fails. The agent loop continues and Claude can retry or explain. An uncaught exception stops the loop and fails the query call.

Return images and structured data

A handler's content array accepts text, image (base64, no data URI prefix), and resource blocks. Set structuredContent to return machine-readable JSON alongside the content. (In Python, structuredContent requires a standalone MCP server rather than the in-process @tool decorator.)

Annotations and scaling

Pass annotations like readOnlyHint: true so Claude can batch parallel-safe calls. Every tool definition consumes context each turn; for dozens of tools, use tool search to load them on demand.

Source

Source citations

Add this badge to your README

Show that Building In-Process MCP Tools with the Claude Agent SDK is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/building-in-process-mcp-tools-with-the-claude-agent-sdk.svg)](https://heyclau.de/entry/guides/building-in-process-mcp-tools-with-the-claude-agent-sdk)

How it compares

Building In-Process MCP Tools with the Claude Agent SDK side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Source provenance, Submitter).

Field

A practical walkthrough of defining in-process custom tools for the Claude Agent SDK with createSdkMcpServer and the tool helper, wiring them into query via mcpServers, allowing them, error handling, and returning images or structured data.

Open dossier

How to design custom tools for the Claude Agent SDK: in-process tool definitions with typed input schemas, permission scoping, structured isError results, and when to reach for an external MCP server instead.

Open dossier

A practical guide for handling secrets when connecting MCP servers and authoring Agent SDK tools in Claude Code: env expansion in .mcp.json, OAuth scope pins, keychain storage, local scope, and redaction before tool arguments reach the model.

Open dossier

A practical walkthrough of slash commands in the Claude Agent SDK. Read the slash_commands array from the system init message, dispatch a command by placing it in the prompt string, handle built-ins like /compact and /clear, and author your own as SKILL.md files with allowed-tools frontmatter.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceDiffersSource-backedSubmission linkedSource submissionSubmission linkedSource submissionSource-backed
SubmitterDiffersJPette1783kiannidevkiannidevJPette1783
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryguidesguidesguidesguides
SourceSource-backedSource-backedSource-backedSource-backed
AuthorJPette1783kiannidevkiannidevJPette1783
Added2026-06-052026-06-142026-06-162026-06-05
Platforms
Harness
Source repo
Safety notesCustom tool handlers run your code in-process whenever Claude calls them; validate inputs and gate destructive actions inside the handler. List each tool in allowedTools (mcp__server__tool) so it runs without a prompt only when you intend; otherwise it goes through the permission flow. Return isError instead of throwing so a failed tool keeps the agent loop alive rather than crashing the whole query. Tool annotations like readOnlyHint are metadata, not enforcement; keep them accurate to what the handler actually does.Tool descriptions are not enforcement—validate destructive inputs inside handlers. Wildcard `mcp__server__*` allowlists expand blast radius; prefer per-tool grants in production. Returning thrown exceptions fails the whole query; use isError responses for recoverable faults.Stdio MCP servers inherit environment variables you pass via --env or .mcp.json env blocks; treat that as handing the server your credentials. HTTP MCP headers and OAuth tokens authenticate outbound calls; a compromised server or overly broad scope can exfiltrate data through tool results. Agent SDK tool descriptions, inputs, and outputs enter model context each turn—never embed live secrets in schemas or sample responses. Project-scoped .mcp.json is designed for version control; use ${VAR} expansion and local scope for machine-specific secrets instead of committing raw keys.Only non-interactive commands are dispatchable through the SDK; the system init message lists which are available in your session. Custom commands can run bash and reference files; scope their allowed-tools frontmatter and review what each command does. Commands that embed bash output or file contents send that data to the model; keep secrets out of referenced files.
Privacy notesIn-process tools run inside your application, so data they touch stays in your process unless the handler sends it elsewhere. Tool descriptions, inputs, and results are sent to the model provider as part of the conversation; avoid placing secrets in them. Every tool definition consumes context on each turn; for large tool sets, load them on demand rather than sending all schemas.Tool schemas and results enter model context every turn—avoid secrets in descriptions or payloads. Large tool sets increase context usage; defer rarely used tools via tool search. Structured outputs may log to host telemetry—redact customer fields at the handler boundary.MCP tool arguments, resource contents, and error messages can contain API keys, JWTs, customer IDs, and internal URLs that flow into session transcripts. OAuth access tokens for remote MCP servers are stored in the macOS Keychain or a credentials file; revoke with Clear authentication in /mcp when offboarding. Agent SDK handlers that call external APIs may log request metadata; redact at the handler boundary before traces or support exports leave your environment. Shared .mcp.json templates should name required variables (for example API_KEY) without example values that look like real credentials.Slash command definitions and any embedded file or bash output are sent to the model provider as prompt content. Custom command files live on disk in .claude/; avoid putting credentials in them or in files they reference with @. Built-in /compact summarizes history; the summary still goes to the provider like the rest of the session.
Prerequisites
  • The Claude Agent SDK installed for Python (claude-agent-sdk) or TypeScript (@anthropic-ai/claude-agent-sdk).
  • For TypeScript, Zod for input schemas; for Python, a dict or JSON Schema per tool.
  • An Anthropic API key or other configured provider credentials for the SDK.
  • Claude Agent SDK installed and a running `query` loop in TypeScript or Python.
  • Zod (TS) or JSON Schema (Python) literacy for tool input contracts.
  • A written list of side effects each custom tool may perform.
  • Decision record template for build vs buy on external MCP integrations.
  • Inventory of MCP servers (stdio, HTTP, or plugin) and any Agent SDK custom tools in your project.
  • Access to .mcp.json, user settings, and environment variables on developer machines.
  • Team policy for secret stores, rotation, and what may appear in version control.
  • Ability to test MCP connections in a non-production profile before granting production credentials.
  • The Claude Agent SDK installed for Python or TypeScript.
  • For custom commands, a .claude/skills/ or legacy .claude/commands/ directory.
  • Awareness that only commands that work without an interactive terminal are dispatchable through the SDK.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.