agent-sdk-quickstart
/agent-sdk-quickstart
Buduje pierwszego agenta w Claude Agent SDK (TypeScript lub Python): uruchamia query, czyta wyniki, ogranicza narzędzia i chroni wywołania hookami.
- Autor
- latestaiagents ↗
- Repozytorium
- agent-skills ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 04.11.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 1
- Skrypty
- 0
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 7
Brak sygnałów. Repozytorium zmienione 04.11.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
Co robi i kiedy
Buduje pierwszego agenta w Claude Agent SDK (TypeScript lub Python): uruchamia query, czyta wyniki, ogranicza narzędzia i chroni wywołania hookami.
Oryginalny opis (EN)
Build a first agent with the Claude Agent SDK (TypeScript or Python): install, run query(), read result messages, restrict tools and permissions, add custom tools through an in-process MCP server, and guard tool calls with hooks. Also explains when to pick the Agent SDK, the Client SDK, or Managed Agents. Use this skill when starting a new agent project, migrating from a hand-written messages.create tool loop, or choosing between the Agent SDK, the Client SDK, and Managed Agents. Activate when: Claude Agent SDK, @anthropic-ai/claude-agent-sdk, claude-agent-sdk, query(), ClaudeAgentOptions, cre
Jak działa
- When to Use
- Choose the Right Surface
- Workflow
- Best Practices
- References
Podgląd SKILL.md
---
name: agent-sdk-quickstart
description: |
Build a first agent with the Claude Agent SDK (TypeScript or Python): install, run query(), read result messages, restrict tools and permissions, add custom tools through an in-process MCP server, and guard tool calls with hooks. Also explains when to pick the Agent SDK, the Client SDK, or Managed Agents.
Use this skill when starting a new agent project, migrating from a hand-written messages.create tool loop, or choosing between the Agent SDK, the Client SDK, and Managed Agents.
Activate when: Claude Agent SDK, @anthropic-ai/claude-agent-sdk, claude-agent-sdk, query(), ClaudeAgentOptions, createSdkMcpServer, build agent, agent SDK quickstart.
---
# Claude Agent SDK Quickstart
**The Agent SDK packages Claude Code's agent loop, built-in tools, permissions, sessions, and hooks as a library for TypeScript and Python. You run it in a process you operate; it drives the loop for you.**
## When to Use
- Building an agent that reads and edits files, runs commands, or searches code in your own environment
- Replacing a hand-written `messages.create` tool loop with a maintained harness
- Adding subagents, hooks, MCP servers, or resumable sessions without building them yourself
## Choose the Right Surface
The SDK docs compare four options:
| You want to | Use |
|-------------|-----|
| Embed Claude Code's agent in your own app, in a process you operate | Agent SDK |
| Interactive development or one-off tasks in a terminal | Claude Code CLI |
| Call the Claude API directly and own the tool loop (or use the client SDK's beta tool runner) | Client SDK (`@anthropic-ai/sdk`, `anthropic`) |
| Have Anthropic host the agent loop and sandbox | Managed Agents (see `managed-agents-api`) |
The Agent SDK and the Client SDK are different packages: the Client SDK has no built-in tools.
## Workflow
### Step 1: Install and authenticate
```bash
npm install @anthropic-ai/claude-agent-sdk # TypeScript
pip install claude-agent-sdk # Python
```
Authenticate with an API key (`ANTHROPIC_API_KEY`) as described in the SDK quickstart. The docs state that third-party products may not offer claude.ai login or rate limits unless previously approved.
### Step 2: Run a first query
`query()` returns an async iterator of messages. The final `result` message carries the outcome, a cost estimate, and the session ID.
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the failing test in src/utils",
options: {
allowedTools: ["Read", "Glob", "Grep", "Edit"],
maxTurns: 20,
},
})) {
if (message.type === "result") {
console.log(message.subtype, message.total_cost_usd, message.session_id);
if (message.subtype === "success") console.log(message.result);
}
}
```
```python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
async for message in query(
prompt="Find and fix the failing test in src/utils",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep", "Edit"], max_turns=20),
):
if isinstance(message, ResultMessage):
print(message.subtype, message.total_cost_usd, message.session_id)
asyncio.run(main())
```
Leave `model` unset to use the default, or pass a model alias or a current full model ID. A single-shot `query()` throws (TypeScript) or raises (Python) after yielding an error result such as `error_max_turns` or `error_max_budget_usd`, so wrap it in try/catch.
### Step 3: Decide what the agent may do
`allowedTools` pre-approves tools; it does not restrict Claude to them. Unlisted tools fall through to the permission mode and your `canUseTool` callback. To remove a tool entirely, put its bare name in `disallowedTools` (or limit built-ins with the `tools` option).
| `permissionMode` | Behavior (per docs) |
|------------------|---------------------|
| `default` | Calls needing approval go to `canUseTool` |
| `dontAsk` | Anything that would prompt is denied |
| `acceptEdits` | File edits and common filesystem commands in the working directory are auto-approved |
| `plan` | Explores and plans without editing source files |
| `auto` | A classifier model reviews actions |
| `bypassPermissions` | Approves nearly everything; use only in an isolated environment |
For a locked-down headless agent, pair `allowedTools` with `permissionMode: "dontAsk"`. Note that `allowedTools` does not constrain `bypassPermissions`.
### Step 4: Add a custom tool
Custom tools run in an in-process MCP server. Pre-approve them by their fully qualified name `mcp__{server}__{tool}`.
```ts
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const lookupOrder = tool(
"lookup_order",
"Look up an order by ID",
{ orderId: z.string().describe("Order ID") },
async ({ orderId }) => ({ content: [{ type: "text", text: JSON.stringify(await db.orders.get(orderId)) }] }),
{ annotations: { readOnlyHint: true } },
);
const orders = createSdkMcpServer({ name: "orders", version: "1.0.0", tools: [lookupOrder] });
for await (const message of query({
prompt: "What is the status of order 1234?",
options: { mcpServers: { orders }, allowedTools: ["mcp__orders__lookup_order"] },
})) {
if (message.type === "result" && message.subtype === "success") console.log(message.result);
}
```
In Python the equivalents are the `@tool` decorator and `create_sdk_mcp_server`. Return `isError: true` (Python: `"is_error": True`) to give Claude a composed error message instead of a raw exception.
### Step 5: Guard tool calls with a hook
Hooks run before every other permission step, and a hook `deny` applies even in `bypassPermissions` mode.
```ts
import { query, type HookCallback, type PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
const protectEnv: HookCallback = async (input) => {
const pre = input as PreToolUseHookInput;
const path = (pre.tool_input as Record<string, unknown>)?.file_path as string | undefined;
if (path?.split("/").pop()?.toLowerCase() === ".env") {
return { hookSpecificOutput: { hookEventName: pre.hook_event_name, permissionDecision: "deny",
permissionDecisionReason: "Cannot modify .env files" } };
}
return {};
};
const options = { hooks: { PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnv] }] } };
```
Matchers match tool names only; check arguments such as `file_path` inside the callback. A `Write|Edit` matcher does not catch the same write done through `Bash`.
### Step 6: Cap spend and turns
Set `maxTurns` and `maxBudgetUsd` (Python: `max_turns`, `max_budget_usd`). The budget is a client-side estimate that can be exceeded slightly, so leave headroom.
## Best Practices
1. Start with read-only tools and `dontAsk`, then widen deliberately
2. Put must-run checks in `PreToolUse` hooks, not only in `canUseTool`
3. Always handle the `result` message and its error subtypes
4. Set `maxTurns` and `maxBudgetUsd` on every unattended run
5. Prefer custom tools with narrow schemas over broad shell access
6. Check the SDK changelog before upgrading; option names and defaults evolve
## References
- Agent SDK overview: https://code.claude.com/docs/en/agent-sdk/overview
- TypeScript reference: https://code.claude.com/docs/en/agent-sdk/typescript
- Python reference: https://code.claude.com/docs/en/agent-sdk/python
- Permissions: https://code.claude.com/docs/en/agent-sdk/permissions
- Custom tools: https://code.claude.com/docs/en/agent-sdk/custom-tools
- Hooks: https://code.claude.com/docs/en/agent-sdk/hooks
- Sessions: https://code.claude.com/docs/en/agent-sdk/sessions
Wersje
W bazie nie ma innych skilli o nazwie agent-sdk-quickstart.
Migawka bazy z 13.11.2026 · wersja paczki 2034e654bfad (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 95claude-agent-sdk
Buduje produkcyjne agenty AI przez Claude Agent SDK w TypeScript lub Pythonie: query(), hooki, subagenty, serwery MCP i uprawnienia. - 90migrating-claude-agent-sdk-to-pydantic-ai
Migruje aplikacje Python z Claude Agent SDK do Pydantic AI, w tym pętlę agenta, sesje, hooki, uprawnienia i podagentów. - 90claude-agent-sdk-tool-integration
Integruje narzędzia, uprawnienia i serwery MCP z agentami Claude przy użyciu Agent SDK. - 100claude-docs
Przeszukuje i czyta lokalnie zapisaną dokumentację Claude: Claude Code CLI, Claude API, Agent SDK w Pythonie i TypeScript, prompt engineering oraz dokumenty platformy Anthropic. - 100claude-agent-sdk
Buduje agentów AI w Claude Agent SDK: funkcje query, ClaudeSDKClient, własne narzędzia, serwery MCP, hooki, uprawnienia, subagenty i sterowanie przeglądarką. - 95claude-sdk
Buduje autonomicznych agentów AI w Claude Agent SDK: computer use, wywoływanie narzędzi, integracja MCP i praktyki produkcyjne dla modeli Anthropic.