vault backup: 2026-04-17 12:40:31
This commit is contained in:
parent
2d4adf6572
commit
2d37e5efc9
35 changed files with 2743 additions and 6 deletions
|
|
@ -23,6 +23,42 @@ created: 2026-04-17
|
|||
- **Local path:** `/Volumes/SSD/Projects/Oliver/Barclays-banner-builder`
|
||||
|
||||
## Sessions
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Ubuntu server with Docker containers, database initialization, and migrations.
|
||||
**Done:** Diagnosed Apache reverse proxy configuration issue where VirtualHost Alias directives were intercepting requests before ProxyPass rules.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for the app on Ubuntu with Docker, Apache reverse proxy, database initialization, and migrations.
|
||||
**Done:** Diagnosed Apache proxy configuration issue by testing FastAPI endpoints directly and confirming the reverse proxy modules needed to be enabled.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Ubuntu server with Docker containers, database initialization, and migrations.
|
||||
**Done:** Debugged FastAPI routing and Apache reverse proxy configuration to resolve 404 errors on the optical-dev domain.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Docker containers on Ubuntu with database initialization and migrations.
|
||||
**Done:** Designed deployment script with git pull and bash execution, verified FastAPI routing in main.py.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Docker containers on Ubuntu with Apache reverse proxy, database initialization, and migrations.
|
||||
**Done:** Analyzed project structure and designed deployment automation with Docker builds, database migrations, and cache management while avoiding WebSockets due to server timeout constraints.
|
||||
|
||||
### 2026-04-17 – Create a deployment script for Ubuntu
|
||||
**Asked:** Create a deployment script for Ubuntu server that builds Docker containers, manages database migrations, and handles frontend updates idempotently.
|
||||
**Done:** Implemented idempotent deployment script that pulls latest code, builds Docker containers with caching, initializes database on first run, and runs migrations.
|
||||
|
||||
### 2026-04-17 – Create deployment script for Ubuntu server
|
||||
**Asked:** Create deployment script for Ubuntu server with Docker, database migrations, and frontend build.
|
||||
**Done:** Identified TypeScript errors in Vite config and fixed unused variable warnings with underscore prefix convention.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Ubuntu server with Docker, database migrations, and frontend file management.
|
||||
**Done:** Analyzed folder structure, created app concept and development plan with Docker deployment on Ubuntu/Apache reverse proxy setup, and provided permission fixes and deployment commands.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Ubuntu server with Docker, database migrations, and frontend asset management.
|
||||
**Done:** Added 184 PNG illustrations to git and verified deployment workflow via pull and bash script execution.
|
||||
|
||||
### 2026-04-17 – Create an idempotent deployment script for
|
||||
**Asked:** Create an idempotent deployment script for Docker containers on Ubuntu with Apache reverse proxy, handling builds, migrations, and frontend updates.
|
||||
**Done:** Deployment script completed and pushed; deployment confirmed working with `git pull origin main && bash deploy.sh` command on server.
|
||||
|
|
@ -87,6 +123,15 @@ created: 2026-04-17
|
|||
## Change Log
|
||||
| Date | Requested | Changed | Files |
|
||||
|------|-----------|---------|-------|
|
||||
| 2026-04-17 | Deployment script & Apache config | Docker build caching, idempotent database init, Alembic migrations, Apache ProxyPass setup | deploy.sh, optical-dev.oliver.solutions.conf |
|
||||
| 2026-04-17 | Deployment script & Apache config | Docker build caching, database migrations, Apache proxy setup | deploy.sh, optical-dev.oliver.solutions.conf |
|
||||
| 2026-04-17 | Deployment script | Docker build caching, database init, migrations, frontend cleanup | deploy.sh, main.py |
|
||||
| 2026-04-17 | Deployment script | Docker build with cache, database init, migrations execution, frontend cleanup | deploy.sh, main.py |
|
||||
| 2026-04-17 | Deployment script | Docker build with cache, DB initialization, Alembic migrations, idempotent logic | deploy.sh, docker-compose.yml |
|
||||
| 2026-04-17 | Deployment script | Docker build with cache, database initialization, Alembic migrations, frontend cleanup | deploy.sh |
|
||||
| 2026-04-17 | Deployment script & TypeScript fixes | Docker build caching, database initialization, Alembic migrations, unused variable handling | deploy.sh, vite.config.ts |
|
||||
| 2026-04-17 | Deployment script & permissions | Docker build caching, database migration automation, file permissions correction, package-lock.json generation | deploy.sh, assets directory permissions, package-lock.json |
|
||||
| 2026-04-17 | Deployment script | Docker build with cache, database initialization and migrations, frontend asset cleanup | deploy.sh, assets/illustrations/ |
|
||||
| 2026-04-17 | Deployment script | Docker builds with cache invalidation, database initialization, Alembic migrations, frontend cleanup | deploy.sh, docker-compose.yml |
|
||||
| 2026-04-17 | Deployment script & volume mount | Add rag-corpus volume to docker-compose, fix mount path | docker-compose.yml, docker-compose.prod.yml |
|
||||
| 2026-04-17 | Deployment script & auth fix | Remove passlib dependency, add bcrypt direct calls, create idempotent deploy script | auth.py, requirements.txt, deploy.sh |
|
||||
|
|
|
|||
|
|
@ -53,3 +53,72 @@ tags: [daily]
|
|||
- 12:24 | `memory-compiler`
|
||||
- **Asked:** Compile a raw article about Agent SDK into the structured wiki knowledge base.
|
||||
- **Done:** Created overview and index files for Agent SDK topic with cross-references to related articles.
|
||||
- 12:26 (<1min) | `memory-compiler`
|
||||
- **Asked:** Compile a new raw wiki article into the knowledge base structure.
|
||||
- **Done:** Updated existing overview.md to credit both source files since the new article was a duplicate.
|
||||
- 12:26 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for Ubuntu server with Docker, database migrations, and frontend asset management.
|
||||
- **Done:** Added 184 PNG illustrations to git and verified deployment workflow via pull and bash script execution.
|
||||
- 12:27 | `memory-compiler`
|
||||
- **Asked:** Compile a new article on the Python API reference into the knowledge base wiki structure.
|
||||
- **Done:** Created structured Python API reference article with function comparisons, SDK methods, and configuration options.
|
||||
- 12:28 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for Ubuntu server with Docker, database migrations, and frontend file management.
|
||||
- **Done:** Analyzed folder structure, created app concept and development plan with Docker deployment on Ubuntu/Apache reverse proxy setup, and provided permission fixes and deployment commands.
|
||||
- 12:29 | `memory-compiler`
|
||||
- **Asked:** Compile a new TypeScript API reference article and update the agent-sdk article count in the master index.
|
||||
- **Done:** Created `wiki/agent-sdk/typescript-api-reference.md` with comprehensive API coverage and incremented article count from 2 to 3.
|
||||
- 12:29 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create deployment script for Ubuntu server with Docker, database migrations, and frontend build.
|
||||
- **Done:** Identified TypeScript errors in Vite config and fixed unused variable warnings with underscore prefix convention.
|
||||
- 12:29 | `memory-compiler`
|
||||
- **Asked:** Compile a raw article into the structured knowledge base wiki.
|
||||
- **Done:** Reviewed wiki structure and master index to understand compilation requirements.
|
||||
- 12:30 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create a deployment script for Ubuntu server that builds Docker containers, manages database migrations, and handles frontend updates idempotently.
|
||||
- **Done:** Implemented idempotent deployment script that pulls latest code, builds Docker containers with caching, initializes database on first run, and runs migrations.
|
||||
- 12:30 | `memory-compiler`
|
||||
- **Asked:** Compile a new article about skills in the Agent SDK into the knowledge base structure.
|
||||
- **Done:** Created and filed the article as `wiki/agent-sdk/skills-in-sdk.md` with discovery mechanics, configuration examples, and SDK vs CLI differences documented.
|
||||
- 12:31 (1min) | `memory-compiler`
|
||||
- **Asked:** Compile a raw wiki article on LLM models into the knowledge base with proper structure and indexing.
|
||||
- **Done:** Created structured wiki article on OpenAI model catalog, topic index, and updated master index with navigation links.
|
||||
- 12:32 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for Docker containers on Ubuntu with Apache reverse proxy, database initialization, and migrations.
|
||||
- **Done:** Analyzed project structure and designed deployment automation with Docker builds, database migrations, and cache management while avoiding WebSockets due to server timeout constraints.
|
||||
- 12:33 | `memory-compiler`
|
||||
- **Asked:** Compile a new article on Agent SDK hooks into the wiki knowledge base with structured documentation.
|
||||
- **Done:** Created wiki article with 25 lifecycle events, four hook types, exit code semantics, matcher system, and five ready-to-paste recipes.
|
||||
- 12:33 (<1min) | `memory-compiler`
|
||||
- **Asked:** Compile a new WezTerm article into the wiki knowledge base and update indices.
|
||||
- **Done:** Created WezTerm CLI reference with subcommands and examples, updated dotfiles index and master index article counts.
|
||||
- 12:34 (1min) | `memory-compiler`
|
||||
- **Asked:** Create a structured wiki article for Claude Code and update the master index.
|
||||
- **Done:** Created overview.md and _index.md in new claude-code/ topic folder, updated master index with new row.
|
||||
- 12:35 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for Docker containers on Ubuntu with database initialization and migrations.
|
||||
- **Done:** Designed deployment script with git pull and bash execution, verified FastAPI routing in main.py.
|
||||
- 12:35 | `memory-compiler`
|
||||
- **Asked:** Compile a new wezterm article into the wiki and update the master index count.
|
||||
- **Done:** Filed wezterm-colors-appearance.md under dotfiles topic and bumped article count from 3 to 4.
|
||||
- 12:36 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for Ubuntu server with Docker containers, database initialization, and migrations.
|
||||
- **Done:** Debugged FastAPI routing and Apache reverse proxy configuration to resolve 404 errors on the optical-dev domain.
|
||||
- 12:36 | `memory-compiler`
|
||||
- **Asked:** Compile a raw wezterm article into the structured knowledge base wiki.
|
||||
- **Done:** Created wezterm config guide with sections on file locations, quick start, live reload, CLI overrides, and modular patterns; updated dotfiles index.
|
||||
- 12:36 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for the app on Ubuntu with Docker, Apache reverse proxy, database initialization, and migrations.
|
||||
- **Done:** Diagnosed Apache proxy configuration issue by testing FastAPI endpoints directly and confirming the reverse proxy modules needed to be enabled.
|
||||
- 12:37 | `memory-compiler`
|
||||
- **Asked:** Compile a new article on agent permissions into the knowledge base wiki structure.
|
||||
- **Done:** Created configure-permissions.md with full permission modes documentation and updated both index files.
|
||||
- 12:38 (1min) | `memory-compiler`
|
||||
- **Asked:** Compile a raw MCP article into the structured wiki knowledge base with updated indices.
|
||||
- **Done:** Created `wiki/claude-code/mcp-integration.md` covering MCP transports, configuration, auth, and enterprise setup, then updated master and topic indices.
|
||||
- 12:38 (<1min) | `Barclays-banner-builder`
|
||||
- **Asked:** Create an idempotent deployment script for Ubuntu server with Docker containers, database initialization, and migrations.
|
||||
- **Done:** Diagnosed Apache reverse proxy configuration issue where VirtualHost Alias directives were intercepting requests before ProxyPass rules.
|
||||
- 12:39 | `memory-compiler`
|
||||
- **Asked:** Compile a new article on MCP integration into the knowledge base wiki structure.
|
||||
- **Done:** Added `mcp-integration.md` to `agent-sdk/` topic with transport types, authentication patterns, and tool management documentation.
|
||||
|
|
|
|||
|
|
@ -28,9 +28,11 @@ This 3-hop pattern works for hundreds of articles without vector search.
|
|||
| [[wiki/qa/_index\|qa/]] | Filed answers to queries (saved with `--file-back`) | 0 |
|
||||
| [[wiki/homelab/_index\|homelab/]] | Self-hosted infra: Proxmox install, IOMMU/PCI passthrough, hypervisor setup, budget builds | 2 |
|
||||
| [[wiki/web-agency/_index\|web-agency/]] | AI-assisted website building & selling: Claude Code, Nanobanana 2, Kling, LaunchPath MCP | 1 |
|
||||
| [[wiki/dotfiles/_index\|dotfiles/]] | Linux terminal ricing: Kitty, Fish, modern Rust CLI tools, LazyVim, unified themes | 1 |
|
||||
| [[wiki/dotfiles/_index\|dotfiles/]] | Linux terminal ricing: Kitty, Fish, WezTerm CLI, modern Rust CLI tools, LazyVim, unified themes | 5 |
|
||||
|
||||
| [[wiki/agent-sdk/_index\|agent-sdk/]] | Claude Agent SDK (formerly Claude Code SDK) — build autonomous AI agents in Python and TypeScript | 1 |
|
||||
| [[wiki/agent-sdk/_index\|agent-sdk/]] | Claude Agent SDK (formerly Claude Code SDK) — build autonomous AI agents in Python and TypeScript | 8 |
|
||||
| [[wiki/llm-models/_index\|llm-models/]] | OpenAI model catalog — GPT-5.x, o-series reasoning, audio/realtime, embeddings, moderation | 1 |
|
||||
| [[wiki/claude-code/_index\|claude-code/]] | Claude Code product docs — install, capabilities, surfaces, MCP, hooks, scheduling, multi-agent | 2 |
|
||||
|
||||
<!-- New topic folders added here automatically as they are created -->
|
||||
<!-- Format: | [[wiki/topic/_index\|topic/]] | One-line description | N articles | -->
|
||||
|
|
|
|||
|
|
@ -15,3 +15,10 @@ Build production AI agents using the same tools, agent loop, and context managem
|
|||
| Article | Summary | Source | Updated |
|
||||
|---------|---------|--------|---------|
|
||||
| [[wiki/agent-sdk/overview\|overview]] | Full SDK overview: built-in tools, features, Client SDK comparison, branding rules | raw/Agent SDK overview 1.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/python-api-reference\|python-api-reference]] | Complete Python API reference: query() vs ClaudeSDKClient, all functions, types, hooks, sandbox, built-in tool I/O shapes | raw/Agent SDK reference - Python.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/typescript-api-reference\|typescript-api-reference]] | Complete TypeScript API reference: query(), startup(), tool(), hooks, permissions, MCP, sandbox, all message and tool I/O types | raw/Agent SDK reference - TypeScript.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/agent-skills-plugins\|agent-skills-plugins]] | Loading plugins in SDK sessions: skills, agents, hooks, MCP servers, namespacing, verification | raw/Agent Skills in the SDK 1.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/skills-in-sdk\|skills-in-sdk]] | Skills as filesystem artifacts: SKILL.md discovery, setting_sources, tool restrictions, troubleshooting | raw/Agent Skills in the SDK.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/hooks-guide\|hooks-guide]] | Full hooks guide: all 25 events, matchers, exit codes, JSON output, prompt/agent/http hook types, recipes, troubleshooting | raw/Automate workflows with hooks.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/configure-permissions\|configure-permissions]] | Permission modes, allow/deny rules, evaluation order, bypassPermissions caveats, subagent inheritance | raw/Configure permissions.md | 2026-04-17 |
|
||||
| [[wiki/agent-sdk/mcp-integration\|mcp-integration]] | MCP server setup: transport types (stdio/HTTP/SSE), allowedTools, auth, tool search, error handling | raw/Connect to external tools with MCP.md | 2026-04-17 |
|
||||
|
|
|
|||
128
wiki/agent-sdk/agent-skills-plugins.md
Normal file
128
wiki/agent-sdk/agent-skills-plugins.md
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
---
|
||||
title: "Agent Skills & Plugins in the SDK"
|
||||
aliases: [sdk-plugins, agent-skills-sdk, claude-sdk-plugins]
|
||||
tags: [agent-sdk, plugins, skills, mcp, hooks, typescript]
|
||||
sources: [raw/Agent Skills in the SDK 1.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# Agent Skills & Plugins in the SDK
|
||||
|
||||
Plugins extend Claude Agent SDK sessions with packaged capabilities — skills, agents, hooks, and MCP servers — loaded from local directories at runtime.
|
||||
|
||||
## What Plugins Contain
|
||||
|
||||
| Component | Description |
|
||||
|-----------|-------------|
|
||||
| **Skills** | Model-invoked capabilities; also callable via `/plugin-name:skill-name` |
|
||||
| **Agents** | Specialized subagents for specific tasks |
|
||||
| **Hooks** | Event handlers that fire on tool use and other events |
|
||||
| **MCP servers** | External tool integrations via Model Context Protocol |
|
||||
|
||||
> `skills/` is the current format. `commands/` is legacy but still supported for backward compatibility.
|
||||
|
||||
## Plugin Directory Structure
|
||||
|
||||
```
|
||||
my-plugin/
|
||||
├── .claude-plugin/
|
||||
│ └── plugin.json # Required manifest
|
||||
├── skills/ # New format — use this
|
||||
│ └── my-skill/
|
||||
│ └── SKILL.md
|
||||
├── commands/ # Legacy format
|
||||
├── agents/
|
||||
├── hooks/
|
||||
│ └── hooks.json
|
||||
└── .mcp.json
|
||||
```
|
||||
|
||||
The path passed to the SDK must point to the **root directory** containing `.claude-plugin/`.
|
||||
|
||||
## Loading Plugins
|
||||
|
||||
```typescript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Hello",
|
||||
options: {
|
||||
plugins: [
|
||||
{ type: "local", path: "./my-plugin" }, // relative
|
||||
{ type: "local", path: "/absolute/path/plugin" } // absolute
|
||||
]
|
||||
}
|
||||
})) { }
|
||||
```
|
||||
|
||||
- Relative paths resolve from the **current working directory**
|
||||
- CLI-installed plugins live at `~/.claude/plugins/` — use their path here too
|
||||
|
||||
## Verifying Plugin Load
|
||||
|
||||
Check the `system` init message:
|
||||
|
||||
```typescript
|
||||
if (message.type === "system" && message.subtype === "init") {
|
||||
console.log(message.plugins); // [{name, path}]
|
||||
console.log(message.slash_commands); // ["/help", "my-plugin:custom-cmd"]
|
||||
}
|
||||
```
|
||||
|
||||
## Using Plugin Skills
|
||||
|
||||
Skills are auto-namespaced as `plugin-name:skill-name`:
|
||||
|
||||
```typescript
|
||||
for await (const message of query({
|
||||
prompt: "/my-plugin:greet",
|
||||
options: {
|
||||
plugins: [{ type: "local", path: "./my-plugin" }]
|
||||
}
|
||||
})) { }
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
```typescript
|
||||
// Dev/testing — load without global install
|
||||
plugins: [{ type: "local", path: "./dev-plugins/my-plugin" }]
|
||||
|
||||
// Team consistency — commit plugin to repo
|
||||
plugins: [{ type: "local", path: "./project-plugins/team-workflows" }]
|
||||
|
||||
// Multiple sources
|
||||
plugins: [
|
||||
{ type: "local", path: "./local-plugin" },
|
||||
{ type: "local", path: "~/.claude/custom-plugins/shared-plugin" }
|
||||
]
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Fix |
|
||||
|---------|-----|
|
||||
| Plugin missing from init message | Check path points to root (`.claude-plugin/` must exist there) |
|
||||
| Skill not invocable | Use full namespace: `plugin-name:skill-name` |
|
||||
| Relative path fails | Run from expected CWD or switch to absolute path |
|
||||
| Invalid manifest | Validate `.claude-plugin/plugin.json` is valid JSON |
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Plugins are loaded per-session via `options.plugins` — no global install required
|
||||
- Skills from plugins are namespaced: `plugin-name:skill-name` to avoid conflicts
|
||||
- Verify loading via `message.type === "system" && message.subtype === "init"`
|
||||
- Prefer `skills/` over `commands/` for new plugin development
|
||||
- CLI-installed plugins (`~/.claude/plugins/`) can be loaded in SDK sessions by path
|
||||
- Plugin root = directory containing `.claude-plugin/plugin.json`
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]] — full SDK feature set and capabilities
|
||||
- [[wiki/agent-sdk/typescript-api-reference|TypeScript API Reference]] — `query()` options, message types, hooks
|
||||
- [[wiki/agent-sdk/python-api-reference|Python API Reference]] — Python equivalent patterns
|
||||
|
||||
---
|
||||
|
||||
*Source: raw/Agent Skills in the SDK 1.md*
|
||||
111
wiki/agent-sdk/configure-permissions.md
Normal file
111
wiki/agent-sdk/configure-permissions.md
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
---
|
||||
title: "Configure Permissions"
|
||||
aliases: [sdk-permissions, agent-permissions, permission-modes]
|
||||
tags: [agent-sdk, permissions, tools, security, hooks]
|
||||
sources: [raw/Configure permissions.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# Configure Permissions
|
||||
|
||||
Control how your agent uses tools using permission modes, allow/deny rules, and hooks. The SDK evaluates these in a fixed order every time Claude requests a tool.
|
||||
|
||||
## Permission Evaluation Order
|
||||
|
||||
When Claude requests a tool, the SDK checks in this sequence:
|
||||
|
||||
1. **Deny rules** (`disallowed_tools`) — always checked first; hard block in every mode
|
||||
2. **Allow rules** (`allowed_tools`) — pre-approves listed tools
|
||||
3. **Hooks** — custom code that can allow, deny, or modify
|
||||
4. **Permission mode** — global fallback behavior
|
||||
5. **`canUseTool` callback** — runtime user approval (only called in `default` mode)
|
||||
|
||||
## Allow and Deny Rules
|
||||
|
||||
| Option | Effect |
|
||||
|--------|--------|
|
||||
| `allowed_tools=["Read", "Grep"]` | Listed tools auto-approved; unlisted tools fall through to mode/callback |
|
||||
| `disallowed_tools=["Bash"]` | Always denied — overrides even `bypassPermissions` |
|
||||
|
||||
- **Deny rules win everywhere** — `disallowed_tools` is checked before the mode, so it blocks even `bypassPermissions`
|
||||
- **`allowed_tools` does not constrain `bypassPermissions`** — unlisted tools still fall through to the mode, which approves everything; use `disallowed_tools` if you need to block specific tools while in bypass mode
|
||||
- Rules can also be set declaratively in `.claude/settings.json` (requires `"project"` in `settingSources`)
|
||||
|
||||
### Locked-down headless pattern
|
||||
|
||||
```typescript
|
||||
const options = {
|
||||
allowedTools: ["Read", "Glob", "Grep"],
|
||||
permissionMode: "dontAsk" // anything not listed → hard deny, never prompts
|
||||
};
|
||||
```
|
||||
|
||||
## Permission Modes
|
||||
|
||||
Set via `permission_mode` (Python) or `permissionMode` (TypeScript) in `query()` options.
|
||||
|
||||
| Mode | Auto-approves | Calls `canUseTool`? | Use when |
|
||||
|------|--------------|---------------------|----------|
|
||||
| `default` | Nothing | Yes (unmatched tools) | Interactive sessions |
|
||||
| `dontAsk` | `allowed_tools` + rule matches only | No — denies instead | Headless, fixed tool surface |
|
||||
| `acceptEdits` | File edits + filesystem ops inside working dir | Yes (other tools) | Prototyping, isolated dir |
|
||||
| `bypassPermissions` | Everything | No | Fully trusted, controlled env |
|
||||
| `plan` | Nothing — no execution | No | Code review, propose-before-apply |
|
||||
| `auto` *(TS only)* | Model classifier decides | No | Eliminate prompts automatically |
|
||||
|
||||
### acceptEdits — auto-approved operations
|
||||
|
||||
- `Edit`, `Write` tools
|
||||
- Shell filesystem commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, `sed`
|
||||
- Only for paths inside `cwd` or `additionalDirectories`; outside paths still prompt
|
||||
|
||||
### bypassPermissions — cautions
|
||||
|
||||
- Hooks still execute and can block
|
||||
- `allowed_tools` has no effect — every tool is approved
|
||||
- `disallowed_tools` and explicit `ask` rules still run before the mode check
|
||||
- Subagents **inherit** this mode and cannot override it — they get full system access
|
||||
|
||||
### plan mode
|
||||
|
||||
- No tool execution at all
|
||||
- Claude may call `AskUserQuestion` to clarify before finalizing the plan
|
||||
- Good for code-review workflows where you approve before anything runs
|
||||
|
||||
## Setting Permission Mode at Runtime
|
||||
|
||||
```python
|
||||
# Python — at query time
|
||||
async for message in query(
|
||||
prompt="Help me refactor this code",
|
||||
options=ClaudeAgentOptions(permission_mode="default"),
|
||||
):
|
||||
...
|
||||
```
|
||||
|
||||
For streaming sessions, the mode can also be changed dynamically while the session is active.
|
||||
|
||||
## Subagent Inheritance
|
||||
|
||||
When the parent uses `bypassPermissions`, `acceptEdits`, or `auto`, all subagents inherit that mode and it cannot be overridden per-subagent. Subagents may have less constrained system prompts, so `bypassPermissions` grants them full autonomous system access.
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Deny rules (`disallowed_tools`) are absolute — they win in every mode, including `bypassPermissions`
|
||||
- `allowed_tools` pre-approves tools but does **not** block unlisted ones; pair with `dontAsk` for a fixed surface
|
||||
- `bypassPermissions` + `allowed_tools` still approves everything — use `disallowed_tools` to actually restrict
|
||||
- `acceptEdits` is the sweet spot for coding agents: fast file edits, normal prompts for shell commands
|
||||
- `plan` mode is zero-risk code review: Claude proposes, nothing executes
|
||||
- Subagents inherit the parent's mode; `bypassPermissions` propagates fully
|
||||
|
||||
## Related Articles
|
||||
|
||||
- [[wiki/agent-sdk/hooks-guide|Hooks Guide]] — custom code that runs in the evaluation chain before the mode check
|
||||
- [[wiki/agent-sdk/python-api-reference|Python API Reference]] — full `ClaudeAgentOptions` type with all permission fields
|
||||
- [[wiki/agent-sdk/typescript-api-reference|TypeScript API Reference]] — `permissionMode`, `allowedTools`, `disallowedTools` options
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]] — SDK capabilities and architecture
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Configure permissions.md` (clipped from https://code.claude.com/docs/en/agent-sdk/permissions)
|
||||
290
wiki/agent-sdk/hooks-guide.md
Normal file
290
wiki/agent-sdk/hooks-guide.md
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
---
|
||||
title: "Claude Code Hooks — Automate Workflows"
|
||||
aliases: [hooks-guide, claude-hooks, lifecycle-hooks]
|
||||
tags: [claude-code, hooks, automation, lifecycle, shell, workflow]
|
||||
sources: [raw/Automate workflows with hooks.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide **deterministic** control — certain actions always happen, regardless of what the LLM decides to do.
|
||||
|
||||
Four hook types exist:
|
||||
- `"type": "command"` — run a shell command (most common)
|
||||
- `"type": "http"` — POST event data to an HTTP endpoint
|
||||
- `"type": "prompt"` — single-turn LLM evaluation (Haiku by default)
|
||||
- `"type": "agent"` — multi-turn subagent with tool access (60s timeout, 50 tool turns)
|
||||
|
||||
---
|
||||
|
||||
## Hook Events Reference
|
||||
|
||||
| Event | When it fires |
|
||||
|-------|--------------|
|
||||
| `SessionStart` | Session begins or resumes |
|
||||
| `UserPromptSubmit` | Prompt submitted, before Claude processes it |
|
||||
| `PreToolUse` | Before a tool call — can block it |
|
||||
| `PostToolUse` | After a tool call succeeds |
|
||||
| `PostToolUseFailure` | After a tool call fails |
|
||||
| `PermissionRequest` | Permission dialog is about to appear |
|
||||
| `PermissionDenied` | Tool call denied by auto-mode classifier |
|
||||
| `Notification` | Claude is waiting for input |
|
||||
| `Stop` | Claude finishes responding |
|
||||
| `StopFailure` | Turn ended due to API error |
|
||||
| `SubagentStart` / `SubagentStop` | Subagent spawned / finished |
|
||||
| `TaskCreated` / `TaskCompleted` | Task lifecycle events |
|
||||
| `ConfigChange` | Config file changed during session |
|
||||
| `CwdChanged` | Working directory changed |
|
||||
| `FileChanged` | Watched file changed on disk |
|
||||
| `PreCompact` / `PostCompact` | Before/after context compaction |
|
||||
| `InstructionsLoaded` | CLAUDE.md or rules file loaded |
|
||||
| `WorktreeCreate` / `WorktreeRemove` | Worktree lifecycle |
|
||||
| `Elicitation` / `ElicitationResult` | MCP server requesting user input |
|
||||
| `TeammateIdle` | Agent team member going idle |
|
||||
| `SessionEnd` | Session terminates |
|
||||
|
||||
---
|
||||
|
||||
## Exit Codes & Output
|
||||
|
||||
| Exit code | Meaning |
|
||||
|-----------|---------|
|
||||
| `0` | Allow. stdout added to Claude's context (for `SessionStart`, `UserPromptSubmit`) |
|
||||
| `2` | Block. Write reason to stderr — Claude receives it as feedback |
|
||||
| Other | Allow, but log error. First line of stderr shown in transcript |
|
||||
|
||||
**Structured JSON output** (exit 0 + JSON to stdout) for fine-grained control:
|
||||
|
||||
```json
|
||||
{
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"permissionDecision": "deny",
|
||||
"permissionDecisionReason": "Use rg instead of grep"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`permissionDecision` values for `PreToolUse`: `"allow"` | `"deny"` | `"ask"` | `"defer"` (non-interactive only)
|
||||
|
||||
> `"allow"` skips the interactive prompt but **does not override** deny rules from settings.
|
||||
|
||||
---
|
||||
|
||||
## Matchers
|
||||
|
||||
Without a matcher, a hook fires on every occurrence of its event. Add `"matcher"` to narrow scope.
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [{ "type": "command", "command": "prettier --write ..." }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Event | Matched field | Example values |
|
||||
|-------|--------------|----------------|
|
||||
| `PreToolUse`, `PostToolUse`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |
|
||||
| `SessionStart` | start source | `startup`, `resume`, `clear`, `compact` |
|
||||
| `SessionEnd` | end reason | `clear`, `resume`, `logout`, `other` |
|
||||
| `ConfigChange` | config source | `user_settings`, `project_settings`, `skills` |
|
||||
| `FileChanged` | literal filenames | `.envrc\|.env` |
|
||||
| `SubagentStart/Stop` | agent type | `Bash`, `Explore`, `Plan` |
|
||||
|
||||
**`if` field** (v2.1.85+): filter by tool name + arguments, using permission rule syntax:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "command",
|
||||
"if": "Bash(git *)",
|
||||
"command": "./.claude/hooks/check-git-policy.sh"
|
||||
}
|
||||
```
|
||||
|
||||
Only works on tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`).
|
||||
|
||||
---
|
||||
|
||||
## Common Recipes
|
||||
|
||||
### Desktop notification when Claude needs input
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"Notification": [{
|
||||
"matcher": "",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Auto-format with Prettier after file edits
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Re-inject context after compaction
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [{
|
||||
"matcher": "compact",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "echo 'Reminder: use Bun, not npm. Run bun test before committing.'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Reload direnv when directory changes
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"CwdChanged": [{
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Auto-approve ExitPlanMode permission
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PermissionRequest": [{
|
||||
"matcher": "ExitPlanMode",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Hook Scopes / Configuration Files
|
||||
|
||||
| File | Scope | Shareable |
|
||||
|------|-------|-----------|
|
||||
| `~/.claude/settings.json` | All projects | No (local machine) |
|
||||
| `.claude/settings.json` | Single project | Yes (commit to repo) |
|
||||
| `.claude/settings.local.json` | Single project | No (gitignored) |
|
||||
| Managed policy settings | Organization-wide | Yes (admin-controlled) |
|
||||
| Plugin `hooks/hooks.json` | When plugin enabled | Yes |
|
||||
| Skill/agent frontmatter | While active | Yes |
|
||||
|
||||
Disable all hooks: set `"disableAllHooks": true` in any settings file.
|
||||
|
||||
---
|
||||
|
||||
## Prompt-Based & Agent-Based Hooks
|
||||
|
||||
**Prompt hook** — LLM evaluates a condition and returns `{"ok": true}` or `{"ok": false, "reason": "..."}`:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"Stop": [{
|
||||
"hooks": [{
|
||||
"type": "prompt",
|
||||
"prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains\"}."
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Agent hook** — spawns a subagent that can read files and run tools before deciding:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"Stop": [{
|
||||
"hooks": [{
|
||||
"type": "agent",
|
||||
"prompt": "Verify that all unit tests pass. Run the test suite. $ARGUMENTS",
|
||||
"timeout": 120
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use prompt hooks when the event data alone is enough. Use agent hooks when you need to inspect actual codebase state.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Fix |
|
||||
|---------|-----|
|
||||
| Hook not firing | Check `/hooks` menu, verify matcher case-sensitivity, confirm correct event type |
|
||||
| "hook error" in transcript | Test manually: `echo '{"tool_name":"Bash",...}' \| ./hook.sh; echo $?` |
|
||||
| `/hooks` shows nothing | Validate JSON (no trailing commas/comments), check file location |
|
||||
| Stop hook infinite loop | Parse `stop_hook_active` from stdin, exit 0 if `true` |
|
||||
| JSON validation failed | Shell profile `echo` statements pollute stdout — wrap in `if [[ $- == *i* ]]` |
|
||||
| Debug | Run `claude --debug-file /tmp/claude.log`, then `tail -f /tmp/claude.log` |
|
||||
|
||||
**Permission interaction:** `PreToolUse` hooks fire before permission-mode checks. A hook returning `deny` blocks even in `bypassPermissions` mode. A hook returning `allow` cannot override deny rules from settings — hooks tighten but cannot loosen.
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Hooks run **deterministically** at lifecycle events — LLM cannot skip them
|
||||
- Use `PreToolUse` + exit 2 to block commands; use `PostToolUse` to react after
|
||||
- `matcher` filters by tool name (regex); `if` field filters by tool name + arguments together
|
||||
- Multiple hooks for the same event run **in parallel**; decisions resolve to most restrictive
|
||||
- `PostToolUse` cannot undo already-executed actions
|
||||
- `PermissionRequest` hooks don't fire in non-interactive (`-p`) mode — use `PreToolUse` instead
|
||||
- Hook stdout goes to Claude's context; stderr goes to Claude as error feedback (on exit 2)
|
||||
- Three LLM-powered types: `prompt` (single call), `agent` (multi-turn with tools), `http` (external service)
|
||||
|
||||
---
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]]
|
||||
- [[wiki/agent-sdk/agent-skills-plugins|Agent Skills & Plugins]]
|
||||
- [[wiki/agent-sdk/skills-in-sdk|Skills in the SDK]]
|
||||
- [[wiki/tech-patterns/_index|Tech Patterns]]
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Automate workflows with hooks.md` — clipped from https://code.claude.com/docs/en/hooks-guide
|
||||
200
wiki/agent-sdk/mcp-integration.md
Normal file
200
wiki/agent-sdk/mcp-integration.md
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
---
|
||||
title: "MCP Integration in Agent SDK"
|
||||
aliases: [mcp-servers, model-context-protocol, agent-mcp]
|
||||
tags: [agent-sdk, mcp, tools, typescript, authentication]
|
||||
sources: [raw/Connect to external tools with MCP.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# MCP Integration in Agent SDK
|
||||
|
||||
The Model Context Protocol (MCP) is an open standard for connecting AI agents to external tools and data sources — databases, GitHub, Slack, APIs — without writing custom tool implementations.
|
||||
|
||||
## Quickstart
|
||||
|
||||
```typescript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Use the docs MCP server to explain what hooks are",
|
||||
options: {
|
||||
mcpServers: {
|
||||
"claude-code-docs": {
|
||||
type: "http",
|
||||
url: "https://code.claude.com/docs/mcp"
|
||||
}
|
||||
},
|
||||
allowedTools: ["mcp__claude-code-docs__*"]
|
||||
}
|
||||
})) {
|
||||
if (message.type === "result" && message.subtype === "success") {
|
||||
console.log(message.result);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adding MCP Servers
|
||||
|
||||
### In code (mcpServers option)
|
||||
|
||||
Pass directly to `query()`:
|
||||
|
||||
```typescript
|
||||
options: {
|
||||
mcpServers: {
|
||||
filesystem: {
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### From `.mcp.json` config file
|
||||
|
||||
Place at project root — loaded automatically when `"project"` is in `settingSources`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Allowing MCP Tools
|
||||
|
||||
MCP tools require **explicit permission** before Claude can call them.
|
||||
|
||||
### Naming convention
|
||||
|
||||
`mcp__<server-name>__<tool-name>` — e.g., `mcp__github__list_issues`
|
||||
|
||||
### allowedTools patterns
|
||||
|
||||
```typescript
|
||||
allowedTools: [
|
||||
"mcp__github__*", // all tools from github server
|
||||
"mcp__db__query", // single tool
|
||||
"mcp__slack__send_message" // single tool
|
||||
]
|
||||
```
|
||||
|
||||
**Use `allowedTools` wildcards, not permission modes:**
|
||||
- `permissionMode: "acceptEdits"` — does NOT auto-approve MCP tools
|
||||
- `permissionMode: "bypassPermissions"` — approves MCP but disables all safety prompts (too broad)
|
||||
- Wildcard in `allowedTools` — grants exactly the server you want, nothing more
|
||||
|
||||
### Discover available tools
|
||||
|
||||
```typescript
|
||||
if (message.type === "system" && message.subtype === "init") {
|
||||
console.log("Available MCP tools:", message.mcp_servers);
|
||||
}
|
||||
```
|
||||
|
||||
## Transport Types
|
||||
|
||||
| Transport | When to use | Config key |
|
||||
|-----------|-------------|------------|
|
||||
| **stdio** | Local process (npx command given) | `command` + `args` |
|
||||
| **HTTP** | Cloud-hosted, non-streaming URL | `type: "http"` + `url` |
|
||||
| **SSE** | Cloud-hosted, streaming URL | `type: "sse"` + `url` |
|
||||
| **SDK MCP** | Custom in-process tools | See custom tools guide |
|
||||
|
||||
### stdio example
|
||||
|
||||
```typescript
|
||||
mcpServers: {
|
||||
github: {
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-github"],
|
||||
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### HTTP/SSE example
|
||||
|
||||
```typescript
|
||||
mcpServers: {
|
||||
"remote-api": {
|
||||
type: "sse",
|
||||
url: "https://api.example.com/mcp/sse",
|
||||
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## MCP Tool Search
|
||||
|
||||
When many tools are configured, definitions can fill the context window. **Tool search is enabled by default** — it withholds tool definitions from context and loads only what Claude needs per turn.
|
||||
|
||||
See [[wiki/agent-sdk/typescript-api-reference|TypeScript API Reference]] for configuration options.
|
||||
|
||||
## Authentication
|
||||
|
||||
### Environment variables (stdio)
|
||||
|
||||
```typescript
|
||||
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }
|
||||
```
|
||||
|
||||
### HTTP headers (remote servers)
|
||||
|
||||
```typescript
|
||||
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` }
|
||||
```
|
||||
|
||||
### OAuth2
|
||||
|
||||
SDK doesn't handle OAuth flows automatically. Complete the flow in your app, then pass the access token via headers:
|
||||
|
||||
```typescript
|
||||
const accessToken = await getAccessTokenFromOAuthFlow();
|
||||
headers: { Authorization: `Bearer ${accessToken}` }
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Check the `system` / `init` message for connection status before the agent starts:
|
||||
|
||||
```typescript
|
||||
if (message.type === "system" && message.subtype === "init") {
|
||||
const failedServers = message.mcp_servers.filter(s => s.status !== "connected");
|
||||
if (failedServers.length > 0) console.warn("Failed:", failedServers);
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Cause | Fix |
|
||||
|---------|-------|-----|
|
||||
| Server shows "failed" | Missing env vars, package not installed, bad connection string, network | Check `init` message `status` field |
|
||||
| Tools not called | Missing `allowedTools` | Add `"mcp__servername__*"` |
|
||||
| Connection timeout | Server slow to start (60s default) | Pre-warm server or use lighter package |
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- MCP tool names follow `mcp__<server>__<tool>` — wildcards with `*` allow all tools from a server
|
||||
- Always use `allowedTools` for MCP access, not `permissionMode`
|
||||
- Three transport types: stdio (local process), HTTP (remote non-streaming), SSE (remote streaming)
|
||||
- Credentials go in `env` (stdio) or `headers` (HTTP/SSE) — never hardcoded
|
||||
- Check `message.type === "system" && message.subtype === "init"` for connection status and tool discovery
|
||||
- Tool search is on by default — prevents context overflow with large tool sets
|
||||
- Default connection timeout is 60 seconds; pre-warm servers that need longer startup
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/agent-sdk/configure-permissions|Configure Permissions]] — `allowedTools`, `disallowedTools`, permission modes
|
||||
- [[wiki/agent-sdk/typescript-api-reference|TypeScript API Reference]] — full `mcpServers` config options
|
||||
- [[wiki/agent-sdk/python-api-reference|Python API Reference]] — Python equivalent
|
||||
- [[wiki/agent-sdk/hooks-guide|Hooks Guide]] — automate workflows alongside MCP tools
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Connect to external tools with MCP.md`
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
title: "Claude Agent SDK — Overview"
|
||||
aliases: [claude-agent-sdk, claude-code-sdk, agent-sdk-overview]
|
||||
tags: [anthropic, claude, agent-sdk, python, typescript, ai-agents]
|
||||
sources: [raw/Agent SDK overview 1.md]
|
||||
sources: [raw/Agent SDK overview 1.md, raw/Agent SDK overview.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
|
@ -110,3 +110,4 @@ Also supports: **Hooks**, **Subagents**, **MCP**, **Permissions**, **Sessions**.
|
|||
## Sources
|
||||
|
||||
- `raw/Agent SDK overview 1.md` — clipped from code.claude.com/docs/en/agent-sdk/overview (2026-04-17)
|
||||
- `raw/Agent SDK overview.md` — duplicate clip, same source page (2026-04-17)
|
||||
|
|
|
|||
357
wiki/agent-sdk/python-api-reference.md
Normal file
357
wiki/agent-sdk/python-api-reference.md
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
---
|
||||
title: "Agent SDK Python API Reference"
|
||||
aliases: [python-sdk-reference, claude-agent-sdk-python]
|
||||
tags: [agent-sdk, python, api-reference, anthropic, claude]
|
||||
sources: [raw/Agent SDK reference - Python.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install claude-agent-sdk
|
||||
```
|
||||
|
||||
## query() vs ClaudeSDKClient
|
||||
|
||||
Two interaction modes — choose based on whether you need conversation continuity.
|
||||
|
||||
| Feature | `query()` | `ClaudeSDKClient` |
|
||||
|---------|-----------|-------------------|
|
||||
| Session | New each call | Reuses same session |
|
||||
| Conversation | Single exchange | Multi-turn context |
|
||||
| Interrupts | No | Yes |
|
||||
| Hooks | Yes | Yes |
|
||||
| Custom Tools | Yes | Yes |
|
||||
| Use Case | One-off tasks | Continuous conversations |
|
||||
|
||||
**Use `query()`** for independent tasks, automation scripts, no history needed.
|
||||
**Use `ClaudeSDKClient`** for chat interfaces, follow-up questions, response-driven logic.
|
||||
|
||||
---
|
||||
|
||||
## Core Functions
|
||||
|
||||
### query()
|
||||
|
||||
```python
|
||||
async def query(
|
||||
*,
|
||||
prompt: str | AsyncIterable[dict[str, Any]],
|
||||
options: ClaudeAgentOptions | None = None,
|
||||
transport: Transport | None = None
|
||||
) -> AsyncIterator[Message]
|
||||
```
|
||||
|
||||
Creates a new session per call. Returns an `AsyncIterator[Message]`.
|
||||
|
||||
```python
|
||||
async for message in query(prompt="Create a Python web server", options=options):
|
||||
print(message)
|
||||
```
|
||||
|
||||
### tool() decorator
|
||||
|
||||
Defines MCP tools with type safety.
|
||||
|
||||
```python
|
||||
@tool("greet", "Greet a user", {"name": str})
|
||||
async def greet(args: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
|
||||
```
|
||||
|
||||
Input schema options:
|
||||
- Simple: `{"text": str, "count": int}`
|
||||
- Full JSON Schema: `{"type": "object", "properties": {...}, "required": [...]}`
|
||||
|
||||
**ToolAnnotations** (optional hints, not security decisions):
|
||||
- `readOnlyHint` — tool doesn't modify environment
|
||||
- `destructiveHint` — tool may perform destructive updates
|
||||
- `idempotentHint` — repeated calls have no extra effect
|
||||
- `openWorldHint` — tool interacts with external entities
|
||||
|
||||
### create_sdk_mcp_server()
|
||||
|
||||
```python
|
||||
def create_sdk_mcp_server(
|
||||
name: str,
|
||||
version: str = "1.0.0",
|
||||
tools: list[SdkMcpTool[Any]] | None = None
|
||||
) -> McpSdkServerConfig
|
||||
```
|
||||
|
||||
Creates an in-process MCP server. Pass result to `ClaudeAgentOptions.mcp_servers`.
|
||||
|
||||
```python
|
||||
calculator = create_sdk_mcp_server(name="calculator", tools=[add, multiply])
|
||||
options = ClaudeAgentOptions(
|
||||
mcp_servers={"calc": calculator},
|
||||
allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],
|
||||
)
|
||||
```
|
||||
|
||||
### Session Management (synchronous)
|
||||
|
||||
| Function | Description |
|
||||
|---------|-------------|
|
||||
| `list_sessions(directory, limit, include_worktrees)` | List past sessions with metadata |
|
||||
| `get_session_messages(session_id, directory, limit, offset)` | Get messages from a past session |
|
||||
| `get_session_info(session_id, directory)` | Metadata for a single session by ID |
|
||||
| `rename_session(session_id, title, directory)` | Set custom title; most recent wins |
|
||||
| `tag_session(session_id, tag, directory)` | Tag a session; pass `None` to clear |
|
||||
|
||||
`SDKSessionInfo` fields: `session_id`, `summary`, `last_modified`, `custom_title`, `first_prompt`, `git_branch`, `cwd`, `tag`, `created_at`.
|
||||
|
||||
---
|
||||
|
||||
## ClaudeSDKClient
|
||||
|
||||
Maintains conversation context across multiple exchanges.
|
||||
|
||||
```python
|
||||
async with ClaudeSDKClient() as client:
|
||||
await client.query("What's the capital of France?")
|
||||
async for message in client.receive_response():
|
||||
...
|
||||
await client.query("What's the population of that city?") # retains context
|
||||
async for message in client.receive_response():
|
||||
...
|
||||
```
|
||||
|
||||
### Key Methods
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `connect(prompt)` | Connect with optional initial prompt |
|
||||
| `query(prompt, session_id)` | Send request in streaming mode |
|
||||
| `receive_messages()` | All messages as async iterator |
|
||||
| `receive_response()` | Messages until (and including) `ResultMessage` |
|
||||
| `interrupt()` | Send stop signal (streaming mode only) |
|
||||
| `set_permission_mode(mode)` | Change permission mode mid-session |
|
||||
| `set_model(model)` | Change model; `None` resets to default |
|
||||
| `rewind_files(user_message_id)` | Restore files to state at message (requires `enable_file_checkpointing=True`) |
|
||||
| `get_mcp_status()` | Status of all MCP servers |
|
||||
| `reconnect_mcp_server(name)` | Retry failed MCP server |
|
||||
| `toggle_mcp_server(name, enabled)` | Enable/disable MCP server mid-session |
|
||||
| `stop_task(task_id)` | Stop a background task |
|
||||
| `disconnect()` | End session |
|
||||
|
||||
### Interrupt pattern
|
||||
|
||||
`interrupt()` sends a stop signal but **does not clear the buffer**. You must drain the interrupted task's messages (including its `ResultMessage` with `subtype="error_during_execution"`) before reading the new response.
|
||||
|
||||
```python
|
||||
await client.interrupt()
|
||||
async for message in client.receive_response(): # drain interrupted task
|
||||
if isinstance(message, ResultMessage): break
|
||||
await client.query("Just say hello instead")
|
||||
async for message in client.receive_response(): # now get new response
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ClaudeAgentOptions
|
||||
|
||||
Key configuration fields:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `allowed_tools` | `list[str]` | Auto-approve these tools (doesn't restrict others) |
|
||||
| `disallowed_tools` | `list[str]` | Always deny; overrides `allowed_tools` and `bypassPermissions` |
|
||||
| `permission_mode` | `PermissionMode` | `"default"`, `"acceptEdits"`, `"plan"`, `"dontAsk"`, `"bypassPermissions"` |
|
||||
| `system_prompt` | `str \| SystemPromptPreset` | Custom string or `{"type":"preset","preset":"claude_code"}` |
|
||||
| `mcp_servers` | `dict[str, McpServerConfig]` | MCP server configs or path to config file |
|
||||
| `cwd` | `str \| Path` | Working directory |
|
||||
| `model` | `str` | Claude model to use |
|
||||
| `max_turns` | `int` | Max agentic turns (tool-use round trips) |
|
||||
| `max_budget_usd` | `float` | Stop when cost estimate reaches this value |
|
||||
| `can_use_tool` | `CanUseTool` | Custom permission callback |
|
||||
| `hooks` | `dict[HookEvent, list[HookMatcher]]` | Hook configurations |
|
||||
| `thinking` | `ThinkingConfig` | `{"type":"adaptive"}`, `{"type":"enabled","budget_tokens":N}`, `{"type":"disabled"}` |
|
||||
| `effort` | `Literal["low","medium","high","xhigh","max"]` | Thinking depth |
|
||||
| `enable_file_checkpointing` | `bool` | Enable file rewinding |
|
||||
| `setting_sources` | `list[SettingSource]` | Which filesystem settings to load (`"user"`, `"project"`, `"local"`); `[]` disables all |
|
||||
| `agents` | `dict[str, AgentDefinition]` | Programmatic subagents |
|
||||
| `sandbox` | `SandboxSettings` | Sandbox configuration |
|
||||
| `output_format` | `dict` | `{"type":"json_schema","schema":{...}}` for structured output |
|
||||
| `fork_session` | `bool` | When resuming, fork instead of continuing original |
|
||||
| `include_partial_messages` | `bool` | Emit `StreamEvent` for partial updates |
|
||||
|
||||
### SettingSource / settings_sources
|
||||
|
||||
```python
|
||||
# Disable all filesystem settings (CI/SDK-only apps)
|
||||
ClaudeAgentOptions(setting_sources=[])
|
||||
|
||||
# Load only shared team settings
|
||||
ClaudeAgentOptions(setting_sources=["project"])
|
||||
|
||||
# Load project settings to include CLAUDE.md
|
||||
ClaudeAgentOptions(
|
||||
system_prompt={"type":"preset","preset":"claude_code"},
|
||||
setting_sources=["project"]
|
||||
)
|
||||
```
|
||||
|
||||
Settings precedence: local > project > user. Programmatic options override filesystem settings. Managed policy settings win over everything.
|
||||
|
||||
---
|
||||
|
||||
## Permission System
|
||||
|
||||
### CanUseTool callback
|
||||
|
||||
```python
|
||||
async def custom_permission(
|
||||
tool_name: str, input_data: dict, context: ToolPermissionContext
|
||||
) -> PermissionResultAllow | PermissionResultDeny:
|
||||
if tool_name == "Write" and "config" in input_data.get("file_path", ""):
|
||||
return PermissionResultAllow(updated_input={**input_data, "file_path": f"./sandbox/{input_data['file_path']}"})
|
||||
return PermissionResultAllow(updated_input=input_data)
|
||||
```
|
||||
|
||||
- `PermissionResultAllow(updated_input=...)` — allow, optionally modify input
|
||||
- `PermissionResultDeny(message="...", interrupt=True)` — deny, optionally interrupt
|
||||
|
||||
---
|
||||
|
||||
## Message Types
|
||||
|
||||
```
|
||||
Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage | StreamEvent | RateLimitEvent
|
||||
ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
|
||||
```
|
||||
|
||||
### ResultMessage key fields
|
||||
|
||||
- `subtype` — `"success"` or `"error_during_execution"`
|
||||
- `total_cost_usd` — client-side cost estimate
|
||||
- `usage` — `{input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens}`
|
||||
- `model_usage` — per-model breakdown (camelCase keys: `inputTokens`, `costUSD`, etc.)
|
||||
- `session_id`, `num_turns`, `duration_ms`
|
||||
|
||||
### Background task messages
|
||||
|
||||
- `TaskStartedMessage` — emitted when background task starts; `task_type`: `"local_bash"`, `"local_agent"`, `"remote_agent"`
|
||||
- `TaskProgressMessage` — periodic updates with `TaskUsage` (tokens, tool_uses, duration_ms)
|
||||
- `TaskNotificationMessage` — completion; `status`: `"completed"`, `"failed"`, `"stopped"`
|
||||
|
||||
### RateLimitEvent
|
||||
|
||||
`status`: `"allowed"`, `"allowed_warning"`, `"rejected"`. Use to warn users or back off.
|
||||
|
||||
---
|
||||
|
||||
## Hook System
|
||||
|
||||
```python
|
||||
HookEvent = Literal[
|
||||
"PreToolUse", "PostToolUse", "PostToolUseFailure",
|
||||
"UserPromptSubmit", "Stop", "SubagentStop", "PreCompact",
|
||||
"Notification", "SubagentStart", "PermissionRequest"
|
||||
]
|
||||
```
|
||||
|
||||
```python
|
||||
options = ClaudeAgentOptions(
|
||||
hooks={
|
||||
"PreToolUse": [
|
||||
HookMatcher(matcher="Bash", hooks=[validate_bash], timeout=120),
|
||||
HookMatcher(hooks=[log_all_tools]), # matches all tools
|
||||
]
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
Hook callback signature: `async def hook(input_data, tool_use_id, context) -> HookJSONOutput`
|
||||
|
||||
Return values:
|
||||
- `{}` — no-op
|
||||
- `{"continue_": False, "stopReason": "..."}` — stop execution
|
||||
- `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", ...}}`
|
||||
- `{"async_": True, "asyncTimeout": 5000}` — defer execution
|
||||
|
||||
Note: Python SDK hooks don't yet support `SessionStart`, `SessionEnd`, `Setup` (TypeScript only).
|
||||
|
||||
---
|
||||
|
||||
## Sandbox Settings
|
||||
|
||||
```python
|
||||
SandboxSettings = {
|
||||
"enabled": True,
|
||||
"autoAllowBashIfSandboxed": True,
|
||||
"excludedCommands": ["docker"], # always bypass sandbox, no model involvement
|
||||
"allowUnsandboxedCommands": True, # model can request bypass via dangerouslyDisableSandbox
|
||||
"network": {
|
||||
"allowLocalBinding": True,
|
||||
"allowUnixSockets": ["/var/run/docker.sock"], # ⚠️ grants full Docker/host access
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Security**: `bypassPermissions` + `allowUnsandboxedCommands=True` lets the model escape the sandbox silently.
|
||||
|
||||
---
|
||||
|
||||
## Built-in Tool Reference (Input/Output shapes)
|
||||
|
||||
| Tool | Key Input | Key Output |
|
||||
|------|-----------|------------|
|
||||
| `Bash` | `command`, `timeout`, `run_in_background` | `output`, `exitCode`, `shellId` |
|
||||
| `Read` | `file_path`, `offset`, `limit` | `content`, `total_lines` |
|
||||
| `Write` | `file_path`, `content` | `bytes_written` |
|
||||
| `Edit` | `file_path`, `old_string`, `new_string`, `replace_all` | `replacements` |
|
||||
| `Glob` | `pattern`, `path` | `matches`, `count` |
|
||||
| `Grep` | `pattern`, `path`, `glob`, `output_mode` | `matches` or `files` |
|
||||
| `WebFetch` | `url`, `prompt` | `response`, `status_code` |
|
||||
| `WebSearch` | `query`, `allowed_domains` | `results`, `total_results` |
|
||||
| `Agent` | `description`, `prompt`, `subagent_type` | `result`, `usage`, `total_cost_usd` |
|
||||
| `Monitor` | `command`, `description`, `timeout_ms`, `persistent` | `taskId` |
|
||||
| `TodoWrite` | `todos[]` with `content`, `status` | `stats` |
|
||||
|
||||
---
|
||||
|
||||
## Type System Notes
|
||||
|
||||
- `@dataclass` types (e.g. `ResultMessage`, `TextBlock`) → attribute access: `msg.result`
|
||||
- `TypedDict` types (e.g. `ThinkingConfigEnabled`, `McpStdioServerConfig`) → dict access: `config["budget_tokens"]`
|
||||
|
||||
---
|
||||
|
||||
## Error Types
|
||||
|
||||
| Exception | When |
|
||||
|-----------|------|
|
||||
| `CLINotFoundError` | Claude Code CLI not installed |
|
||||
| `CLIConnectionError` | Connection to Claude Code failed |
|
||||
| `ProcessError` | Claude Code process failed (`exit_code`, `stderr` attrs) |
|
||||
| `CLIJSONDecodeError` | JSON parsing failed (`line`, `original_error` attrs) |
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- `query()` = stateless one-shot; `ClaudeSDKClient` = stateful multi-turn conversation
|
||||
- After `interrupt()`, drain the buffer with `receive_response()` before sending a new query
|
||||
- `disallowed_tools` overrides everything including `bypassPermissions`
|
||||
- `allowed_tools` auto-approves but does NOT restrict — use `disallowed_tools` to block
|
||||
- `setting_sources=[]` disables all filesystem settings (good for CI and SDK-only apps)
|
||||
- `ThinkingConfig` and `McpServerConfig` variants are `TypedDict` (dict at runtime, not objects)
|
||||
- `SdkBeta: "context-1m-2025-08-07"` is retired after 2026-04-30; Claude Sonnet/Opus 4.6+ have 1M context natively
|
||||
- Sandbox + `allowUnixSockets` for Docker socket grants full host access — high risk
|
||||
- Hook callbacks use `continue_` and `async_` (with underscores) in Python; SDK converts to `continue`/`async` for CLI
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- [raw/Agent SDK reference - Python.md](raw/Agent%20SDK%20reference%20-%20Python.md)
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]]
|
||||
- [[wiki/tech-patterns/ai-patterns|AI Patterns]]
|
||||
- [[wiki/architecture/multi-agent-ai|Multi-Agent AI Architecture]]
|
||||
123
wiki/agent-sdk/skills-in-sdk.md
Normal file
123
wiki/agent-sdk/skills-in-sdk.md
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
---
|
||||
title: "Agent Skills in the SDK — Configuration & Discovery"
|
||||
aliases: [sdk-skills, skills-setting-sources, skill-md-sdk]
|
||||
tags: [agent-sdk, skills, python, typescript, configuration, filesystem]
|
||||
sources: [raw/Agent Skills in the SDK.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# Agent Skills in the SDK — Configuration & Discovery
|
||||
|
||||
Skills are model-invoked capabilities defined as `SKILL.md` files on the filesystem. The SDK discovers them at startup via `setting_sources` / `settingSources` — **not** through a programmatic registration API.
|
||||
|
||||
## How Skills Are Discovered
|
||||
|
||||
Skills are loaded from filesystem directories determined by `setting_sources`:
|
||||
|
||||
| Source value | Directory scanned |
|
||||
|---|---|
|
||||
| `"user"` | `~/.claude/skills/` |
|
||||
| `"project"` | `<cwd>/.claude/skills/` |
|
||||
| plugin | bundled inside the plugin directory |
|
||||
|
||||
Default `query()` options load both `user` and `project` sources automatically. If you set `setting_sources` explicitly, you must include `"user"` and/or `"project"` to keep skill discovery.
|
||||
|
||||
## Minimal Setup (Python)
|
||||
|
||||
```python
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
options = ClaudeAgentOptions(
|
||||
cwd="/path/to/project", # must contain .claude/skills/
|
||||
setting_sources=["user", "project"],
|
||||
allowed_tools=["Skill", "Read", "Write", "Bash"],
|
||||
)
|
||||
|
||||
async for message in query(prompt="Help me process this PDF", options=options):
|
||||
print(message)
|
||||
```
|
||||
|
||||
Two requirements:
|
||||
1. `"Skill"` in `allowed_tools`
|
||||
2. `setting_sources` includes `"user"` or `"project"` (or both)
|
||||
|
||||
## Skill Directory Structure
|
||||
|
||||
```
|
||||
.claude/skills/
|
||||
└── processing-pdfs/
|
||||
└── SKILL.md ← instructions + description in YAML frontmatter
|
||||
```
|
||||
|
||||
The `description` field in `SKILL.md` frontmatter is what Claude reads to decide when to invoke the skill.
|
||||
|
||||
## Tool Restrictions — SDK vs CLI
|
||||
|
||||
| Context | `allowed-tools` in SKILL.md | Effect |
|
||||
|---|---|---|
|
||||
| Claude Code CLI | Supported | Restricts tools inside the skill |
|
||||
| SDK (`query()`) | **Ignored** | Has no effect |
|
||||
|
||||
In the SDK, tool access is controlled exclusively via the top-level `allowed_tools` option:
|
||||
|
||||
```python
|
||||
options = ClaudeAgentOptions(
|
||||
setting_sources=["user", "project"],
|
||||
allowed_tools=["Skill", "Read", "Grep", "Glob"],
|
||||
# Without canUseTool callback, anything not listed is denied
|
||||
)
|
||||
```
|
||||
|
||||
## Discovering Available Skills at Runtime
|
||||
|
||||
```python
|
||||
options = ClaudeAgentOptions(
|
||||
setting_sources=["user", "project"],
|
||||
allowed_tools=["Skill"],
|
||||
)
|
||||
async for message in query(prompt="What Skills are available?", options=options):
|
||||
print(message)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Skills not found**
|
||||
|
||||
```python
|
||||
# Wrong — skills not loaded
|
||||
ClaudeAgentOptions(setting_sources=[], allowed_tools=["Skill"])
|
||||
|
||||
# Correct
|
||||
ClaudeAgentOptions(setting_sources=["user", "project"], allowed_tools=["Skill"])
|
||||
```
|
||||
|
||||
Also verify:
|
||||
```sh
|
||||
ls .claude/skills/*/SKILL.md # project skills
|
||||
ls ~/.claude/skills/*/SKILL.md # user skills
|
||||
```
|
||||
|
||||
**Skill not being invoked**
|
||||
- Confirm `"Skill"` is in `allowed_tools`
|
||||
- Check the `description` field in `SKILL.md` — must be specific and keyword-rich
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Skills **must** be filesystem artifacts (`SKILL.md`) — no programmatic registration API exists
|
||||
- `setting_sources=["user", "project"]` is required for skill discovery; an empty list disables it
|
||||
- `"Skill"` must appear in `allowed_tools` or Claude cannot invoke any skill
|
||||
- `allowed-tools` frontmatter in `SKILL.md` is **CLI-only** — ignored by the SDK
|
||||
- The `cwd` option determines which `.claude/skills/` project directory is scanned
|
||||
- For plugin-bundled skills, see [[wiki/agent-sdk/agent-skills-plugins|Agent Skills & Plugins in the SDK]]
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/agent-sdk/agent-skills-plugins|Agent Skills & Plugins in the SDK]] — loading skills bundled inside plugins
|
||||
- [[wiki/agent-sdk/python-api-reference|Python API Reference]] — full `ClaudeAgentOptions` type reference
|
||||
- [[wiki/agent-sdk/typescript-api-reference|TypeScript API Reference]] — `settingSources`, `allowedTools`, `canUseTool`
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]] — full SDK feature set
|
||||
|
||||
---
|
||||
|
||||
*Source: raw/Agent Skills in the SDK.md*
|
||||
362
wiki/agent-sdk/typescript-api-reference.md
Normal file
362
wiki/agent-sdk/typescript-api-reference.md
Normal file
|
|
@ -0,0 +1,362 @@
|
|||
---
|
||||
title: "Agent SDK TypeScript API Reference"
|
||||
aliases: [typescript-sdk-reference, agent-sdk-typescript, ts-api-reference]
|
||||
tags: [agent-sdk, typescript, api-reference, anthropic, claude, mcp, hooks]
|
||||
sources: [raw/Agent SDK reference - TypeScript.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# Agent SDK — TypeScript API Reference
|
||||
|
||||
Complete API reference for `@anthropic-ai/claude-agent-sdk` (TypeScript/Node.js).
|
||||
|
||||
> A simplified V2 interface with `send()` and `stream()` patterns is in preview. This doc covers the current stable API.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @anthropic-ai/claude-agent-sdk
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Functions
|
||||
|
||||
### query()
|
||||
|
||||
Primary entry point. Returns an async generator that streams `SDKMessage` objects.
|
||||
|
||||
```typescript
|
||||
function query({
|
||||
prompt: string | AsyncIterable<SDKUserMessage>,
|
||||
options?: Options
|
||||
}): Query;
|
||||
```
|
||||
|
||||
- `prompt` — string or async iterable (for streaming multi-turn input)
|
||||
- `options` — see [[#Options]] below
|
||||
- Returns a `Query` object (extends `AsyncGenerator<SDKMessage>`)
|
||||
|
||||
### startup()
|
||||
|
||||
Pre-warms the CLI subprocess before a prompt is ready. Moves spawn + handshake cost off the critical path.
|
||||
|
||||
```typescript
|
||||
const warm = await startup({ options: { maxTurns: 3 } });
|
||||
for await (const msg of warm.query("What files are here?")) { ... }
|
||||
```
|
||||
|
||||
- Returns `Promise<WarmQuery>`
|
||||
- `initializeTimeoutMs` defaults to `60000` ms
|
||||
- `WarmQuery.query()` can only be called once; use `WarmQuery.close()` to discard
|
||||
- Implements `AsyncDisposable` — supports `await using` for auto-cleanup
|
||||
|
||||
### tool()
|
||||
|
||||
Creates a type-safe MCP tool definition using a Zod schema.
|
||||
|
||||
```typescript
|
||||
const myTool = tool("search", "Search the web", { query: z.string() },
|
||||
async ({ query }) => ({ content: [{ type: "text", text: `Results for: ${query}` }] }),
|
||||
{ annotations: { readOnlyHint: true, openWorldHint: true } }
|
||||
);
|
||||
```
|
||||
|
||||
Supports both Zod 3 and Zod 4. Pass to `createSdkMcpServer()`.
|
||||
|
||||
### createSdkMcpServer()
|
||||
|
||||
Creates an in-process MCP server.
|
||||
|
||||
```typescript
|
||||
createSdkMcpServer({ name: "my-server", version: "1.0", tools: [myTool] })
|
||||
```
|
||||
|
||||
### Session Management
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `listSessions(options?)` | List past sessions; filter by `dir`, `limit`, `includeWorktrees` |
|
||||
| `getSessionMessages(sessionId, options?)` | Read messages from a session transcript |
|
||||
| `getSessionInfo(sessionId, options?)` | Fetch metadata for one session by ID |
|
||||
| `renameSession(sessionId, title, options?)` | Set a custom title (most recent wins) |
|
||||
| `tagSession(sessionId, tag \| null, options?)` | Tag or clear tag on a session |
|
||||
|
||||
`listSessions` returns `SDKSessionInfo[]` sorted by `lastModified` descending.
|
||||
|
||||
---
|
||||
|
||||
## Options
|
||||
|
||||
Key properties for `query()` / `startup()`:
|
||||
|
||||
| Property | Type | Default | Notes |
|
||||
|----------|------|---------|-------|
|
||||
| `prompt` | `string` | — | Initial prompt |
|
||||
| `model` | `string` | CLI default | Claude model to use |
|
||||
| `maxTurns` | `number` | unlimited | Max tool-use round trips |
|
||||
| `effort` | `'low'\|'medium'\|'high'\|'xhigh'\|'max'` | `'high'` | Guides thinking depth |
|
||||
| `thinking` | `ThinkingConfig` | `{type:'adaptive'}` | `adaptive` / `enabled` / `disabled` |
|
||||
| `permissionMode` | `PermissionMode` | `'default'` | See [[#Permission Mode]] |
|
||||
| `allowedTools` | `string[]` | `[]` | Auto-approve (does NOT restrict) |
|
||||
| `disallowedTools` | `string[]` | `[]` | Always deny; overrides allowedTools |
|
||||
| `canUseTool` | `CanUseTool` | — | Custom permission function |
|
||||
| `mcpServers` | `Record<string, McpServerConfig>` | `{}` | MCP server map |
|
||||
| `agents` | `Record<string, AgentDefinition>` | — | Programmatic subagent definitions |
|
||||
| `systemPrompt` | `string \| {type:'preset'}` | minimal | Use `preset: 'claude_code'` to load full CC prompt |
|
||||
| `settingSources` | `SettingSource[]` | all | Control which filesystem settings load |
|
||||
| `resume` | `string` | — | Resume a session by ID |
|
||||
| `sessionId` | `string` | auto | Pin session to specific UUID |
|
||||
| `persistSession` | `boolean` | `true` | Set `false` to skip disk persistence |
|
||||
| `maxBudgetUsd` | `number` | — | Hard cost cap (client-side estimate) |
|
||||
| `enableFileCheckpointing` | `boolean` | `false` | Enable file rewind |
|
||||
| `hooks` | `Partial<Record<HookEvent, HookCallbackMatcher[]>>` | `{}` | Programmatic hook callbacks |
|
||||
| `sandbox` | `SandboxSettings` | — | Sandbox configuration |
|
||||
| `plugins` | `SdkPluginConfig[]` | `[]` | Local plugin paths |
|
||||
| `outputFormat` | `{type:'json_schema', schema}` | — | Structured output schema |
|
||||
| `promptSuggestions` | `boolean` | `false` | Emit predicted next prompt after each turn |
|
||||
|
||||
### settingSources
|
||||
|
||||
Controls which filesystem settings are loaded. Precedence: local > project > user > managed policy (always loaded).
|
||||
|
||||
```typescript
|
||||
settingSources: [] // SDK-only — no filesystem settings
|
||||
settingSources: ["project"] // CI: only .claude/settings.json
|
||||
settingSources: ["user","project","local"] // Default (same as omitting)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Query Object
|
||||
|
||||
The object returned by `query()` — extends `AsyncGenerator<SDKMessage>`.
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `interrupt()` | Interrupt (streaming input mode only) |
|
||||
| `rewindFiles(msgId, {dryRun?})` | Restore files to checkpoint; requires `enableFileCheckpointing` |
|
||||
| `setPermissionMode(mode)` | Change permission mode mid-session |
|
||||
| `setModel(model?)` | Change model mid-session |
|
||||
| `streamInput(stream)` | Feed async iterable of `SDKUserMessage` for multi-turn |
|
||||
| `stopTask(taskId)` | Stop a background task |
|
||||
| `setMcpServers(servers)` | Dynamically replace MCP servers; returns `McpSetServersResult` |
|
||||
| `mcpServerStatus()` | Status of all connected MCP servers |
|
||||
| `supportedModels()` | Available models with display info |
|
||||
| `supportedAgents()` | Available subagents as `AgentInfo[]` |
|
||||
| `accountInfo()` | Authenticated account info |
|
||||
| `initializationResult()` | Full init data (commands, agents, models, etc.) |
|
||||
| `close()` | Terminate process and clean up |
|
||||
|
||||
---
|
||||
|
||||
## Permission Types
|
||||
|
||||
### PermissionMode
|
||||
|
||||
```
|
||||
"default" Standard prompting
|
||||
"acceptEdits" Auto-accept file edits
|
||||
"bypassPermissions" Skip all checks (requires allowDangerouslySkipPermissions)
|
||||
"plan" Planning only — no execution
|
||||
"dontAsk" Deny if not pre-approved
|
||||
"auto" Model classifier approves/denies each tool call
|
||||
```
|
||||
|
||||
### CanUseTool
|
||||
|
||||
Custom permission callback with full context:
|
||||
|
||||
```typescript
|
||||
type CanUseTool = (
|
||||
toolName: string,
|
||||
input: Record<string, unknown>,
|
||||
options: { signal, suggestions?, blockedPath?, decisionReason?, toolUseID, agentID? }
|
||||
) => Promise<{ behavior: "allow"; updatedInput?; updatedPermissions? }
|
||||
| { behavior: "deny"; message; interrupt? }>;
|
||||
```
|
||||
|
||||
### PermissionUpdate operations
|
||||
|
||||
`addRules` / `replaceRules` / `removeRules` / `setMode` / `addDirectories` / `removeDirectories`
|
||||
|
||||
Destinations: `"userSettings"` | `"projectSettings"` | `"localSettings"` | `"session"` | `"cliArg"`
|
||||
|
||||
---
|
||||
|
||||
## Message Types
|
||||
|
||||
`SDKMessage` is a discriminated union on the `type` field:
|
||||
|
||||
| Type | Subtype | Description |
|
||||
|------|---------|-------------|
|
||||
| `assistant` | — | Assistant response; `message` is `BetaMessage` from Anthropic SDK |
|
||||
| `user` | — | User input; set `shouldQuery: false` to inject context without triggering a turn |
|
||||
| `result` | `success` / `error_*` | Final result with cost, usage, turns, structured output |
|
||||
| `system` | `init` | Session initialization (tools, MCP servers, model, permission mode) |
|
||||
| `system` | `compact_boundary` | Conversation compaction event |
|
||||
| `system` | `status` | Status update (e.g., `"compacting"`) |
|
||||
| `system` | `task_started` / `task_progress` / `task_notification` | Background task lifecycle |
|
||||
| `system` | `hook_started` / `hook_progress` / `hook_response` | Hook execution events |
|
||||
| `system` | `plugin_install` | Plugin install progress |
|
||||
| `system` | `files_persisted` | File checkpointing event |
|
||||
| `stream_event` | — | Partial assistant message (only with `includePartialMessages: true`) |
|
||||
| `tool_progress` | — | Periodic tool execution progress |
|
||||
| `rate_limit_event` | — | Rate limit status |
|
||||
| `prompt_suggestion` | — | Predicted next prompt (only with `promptSuggestions: true`) |
|
||||
| `auth_status` | — | Auth flow events |
|
||||
|
||||
---
|
||||
|
||||
## Hook System
|
||||
|
||||
Hook events fire at lifecycle points. Attach via `options.hooks` in `query()`.
|
||||
|
||||
### HookEvent values
|
||||
|
||||
`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Notification`, `UserPromptSubmit`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStart`, `SubagentStop`, `PreCompact`, `PermissionRequest`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`
|
||||
|
||||
### HookCallbackMatcher
|
||||
|
||||
```typescript
|
||||
interface HookCallbackMatcher {
|
||||
matcher?: string; // Optional glob/regex filter
|
||||
hooks: HookCallback[];
|
||||
timeout?: number; // Seconds
|
||||
}
|
||||
```
|
||||
|
||||
### SyncHookJSONOutput — key fields
|
||||
|
||||
- `continue`: `false` to block
|
||||
- `decision`: `"approve"` | `"block"`
|
||||
- `hookSpecificOutput.permissionDecision`: `"allow"` | `"deny"` | `"ask"` (for `PreToolUse`)
|
||||
- `hookSpecificOutput.additionalContext`: inject context into the next turn
|
||||
- `hookSpecificOutput.updatedInput`: modify tool input (for `PreToolUse`)
|
||||
- `hookSpecificOutput.updatedMCPToolOutput`: modify MCP result (for `PostToolUse`)
|
||||
|
||||
---
|
||||
|
||||
## AgentDefinition
|
||||
|
||||
Programmatically define subagents in `options.agents`:
|
||||
|
||||
```typescript
|
||||
type AgentDefinition = {
|
||||
description: string; // When to use this agent (required)
|
||||
prompt: string; // System prompt (required)
|
||||
tools?: string[];
|
||||
disallowedTools?: string[];
|
||||
model?: "sonnet" | "opus" | "haiku" | "inherit";
|
||||
mcpServers?: AgentMcpServerSpec[];
|
||||
skills?: string[];
|
||||
maxTurns?: number;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP Server Config Types
|
||||
|
||||
| Type | Transport | Key fields |
|
||||
|------|-----------|------------|
|
||||
| `McpStdioServerConfig` | stdio (default) | `command`, `args?`, `env?` |
|
||||
| `McpSSEServerConfig` | SSE | `url`, `headers?` |
|
||||
| `McpHttpServerConfig` | HTTP | `url`, `headers?` |
|
||||
| `McpSdkServerConfigWithInstance` | in-process | `name`, `instance` |
|
||||
| `McpClaudeAIProxyServerConfig` | proxy | `url`, `id` |
|
||||
|
||||
---
|
||||
|
||||
## Built-in Tool I/O Types
|
||||
|
||||
All exported from `@anthropic-ai/claude-agent-sdk` as `ToolInputSchemas` / `ToolOutputSchemas`.
|
||||
|
||||
### Key tool input shapes
|
||||
|
||||
| Tool | Key inputs |
|
||||
|------|-----------|
|
||||
| `Bash` | `command`, `timeout?`, `run_in_background?`, `dangerouslyDisableSandbox?` |
|
||||
| `Read` | `file_path`, `offset?`, `limit?`, `pages?` |
|
||||
| `Write` | `file_path`, `content` |
|
||||
| `Edit` | `file_path`, `old_string`, `new_string`, `replace_all?` |
|
||||
| `Glob` | `pattern`, `path?` |
|
||||
| `Grep` | `pattern`, `path?`, `glob?`, `output_mode?`, `multiline?` |
|
||||
| `Agent` | `description`, `prompt`, `subagent_type`, `run_in_background?`, `isolation?` |
|
||||
| `WebSearch` | `query`, `allowed_domains?`, `blocked_domains?` |
|
||||
| `TodoWrite` | `todos: [{content, status, activeForm}]` |
|
||||
| `EnterWorktree` | `name?` or `path?` (mutually exclusive) |
|
||||
|
||||
### SDKResultMessage cost fields
|
||||
|
||||
- `total_cost_usd` — client-side estimate (see cost-tracking docs for accuracy caveats)
|
||||
- `modelUsage` — per-model breakdown with `inputTokens`, `outputTokens`, `costUSD`, `contextWindow`
|
||||
|
||||
---
|
||||
|
||||
## Sandbox Settings
|
||||
|
||||
```typescript
|
||||
sandbox: {
|
||||
enabled: true,
|
||||
autoAllowBashIfSandboxed: true, // default true
|
||||
excludedCommands: ["docker"], // always bypass, no model control
|
||||
allowUnsandboxedCommands: true, // model can request dangerouslyDisableSandbox
|
||||
network: {
|
||||
allowedDomains: ["api.example.com"],
|
||||
allowLocalBinding: true,
|
||||
allowUnixSockets: ["/var/run/docker.sock"] // ⚠️ grants full Docker/host access
|
||||
},
|
||||
filesystem: {
|
||||
allowWrite: ["/tmp/*"],
|
||||
denyRead: ["/etc/secrets"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**`excludedCommands` vs `allowUnsandboxedCommands`:** excluded commands always bypass silently; `allowUnsandboxedCommands` lets the model *request* bypass at runtime, which then falls through to `canUseTool`.
|
||||
|
||||
> **Warning:** `bypassPermissions` + `allowUnsandboxedCommands` = model can escape sandbox silently.
|
||||
|
||||
---
|
||||
|
||||
## ThinkingConfig
|
||||
|
||||
```typescript
|
||||
{ type: "adaptive" } // Model decides when/how much (Opus 4.6+)
|
||||
{ type: "enabled", budgetTokens?: number } // Fixed token budget
|
||||
{ type: "disabled" }
|
||||
```
|
||||
|
||||
`effort` option also guides thinking depth without hard token limits.
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- **`query()`** is the main entry point — async generator returning `SDKMessage` stream
|
||||
- **`startup()`** pre-warms the subprocess for latency-sensitive applications; returns `WarmQuery`
|
||||
- **`tool()` + `createSdkMcpServer()`** let you define in-process MCP tools with Zod schemas
|
||||
- **`settingSources: []`** for fully programmatic SDK apps; `["project"]` for CI consistency
|
||||
- **`canUseTool`** callback gives fine-grained runtime control over tool permissions
|
||||
- **Hooks** (`options.hooks`) run in-process; can block tools, modify inputs/outputs, inject context
|
||||
- **`AgentDefinition`** allows defining subagents programmatically without CLAUDE.md / settings files
|
||||
- **`SDKResultMessage`** contains `total_cost_usd`, `usage`, `modelUsage` — always a client-side estimate
|
||||
- **Sandbox** `excludedCommands` is static; `allowUnsandboxedCommands` is model-controlled — don't combine with `bypassPermissions`
|
||||
- **`rewindFiles()`** requires `enableFileCheckpointing: true`; use `dryRun` to preview
|
||||
- **`setMcpServers()`** on a live Query object replaces the MCP server set mid-session
|
||||
|
||||
---
|
||||
|
||||
## Related Articles
|
||||
|
||||
- [[wiki/agent-sdk/python-api-reference|Python API Reference]] — Python equivalent of this reference
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]] — SDK capabilities, built-in tools, Client SDK comparison
|
||||
- [[wiki/tech-patterns/ai-patterns|AI Patterns]] — How agents are wired into Oliver Agency projects
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Agent SDK reference - TypeScript.md` (clipped from https://code.claude.com/docs/en/agent-sdk/typescript)
|
||||
18
wiki/claude-code/_index.md
Normal file
18
wiki/claude-code/_index.md
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
title: "Claude Code Index"
|
||||
description: "Claude Code product docs — installation, capabilities, surfaces, customization, scheduling, and CLI patterns"
|
||||
tags: [index, claude-code, anthropic, cli, agentic]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# Claude Code
|
||||
|
||||
Claude Code is Anthropic's agentic coding assistant. Works across terminal, IDE, desktop, web, and mobile — reads your codebase, edits files, runs commands, and integrates with dev tools.
|
||||
|
||||
## Articles
|
||||
|
||||
| Article | Summary | Source | Updated |
|
||||
|---------|---------|--------|---------|
|
||||
| [[wiki/claude-code/overview\|overview]] | Full product overview: install, capabilities (tasks, git, MCP, hooks, scheduling, multi-agent), all surfaces | raw/Claude Code overview.md | 2026-04-17 |
|
||||
| [[wiki/claude-code/mcp-integration\|mcp-integration]] | MCP setup, transports, scopes, OAuth, tool search, channels, managed enterprise config, 100+ server list | raw/Connect Claude Code to tools via MCP.md | 2026-04-17 |
|
||||
260
wiki/claude-code/mcp-integration.md
Normal file
260
wiki/claude-code/mcp-integration.md
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
---
|
||||
title: "MCP Integration in Claude Code"
|
||||
aliases: [mcp-servers, model-context-protocol, claude-mcp]
|
||||
tags: [claude-code, mcp, integrations, tools, authentication, enterprise]
|
||||
sources: [raw/Connect Claude Code to tools via MCP.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# MCP Integration in Claude Code
|
||||
|
||||
Claude Code connects to external tools, databases, and APIs via the **Model Context Protocol (MCP)** — an open standard for AI-tool integrations. Instead of pasting data into chat, you connect a server once and Claude reads/acts on the system directly.
|
||||
|
||||
## What MCP Enables
|
||||
|
||||
Claude Code can:
|
||||
- Implement features from issue trackers (JIRA → GitHub PR)
|
||||
- Analyze monitoring data (Sentry, Statsig, PostHog)
|
||||
- Query databases (PostgreSQL, BigQuery, Supabase)
|
||||
- Integrate design tools (Figma → code)
|
||||
- Automate workflows (Gmail drafts, Slack messages)
|
||||
- React to external events via **channels** (Telegram, webhooks, Discord)
|
||||
|
||||
## Installing MCP Servers
|
||||
|
||||
### Three Transport Types
|
||||
|
||||
| Transport | When to Use | Command |
|
||||
|-----------|-------------|---------|
|
||||
| HTTP (recommended) | Cloud services, remote APIs | `claude mcp add --transport http <name> <url>` |
|
||||
| SSE | Deprecated — use HTTP instead | `claude mcp add --transport sse <name> <url>` |
|
||||
| stdio | Local processes, direct system access | `claude mcp add <name> -- <command> [args]` |
|
||||
|
||||
```sh
|
||||
# HTTP example
|
||||
claude mcp add --transport http notion https://mcp.notion.com/mcp
|
||||
|
||||
# With auth header
|
||||
claude mcp add --transport http secure-api https://api.example.com/mcp \
|
||||
--header "Authorization: Bearer your-token"
|
||||
|
||||
# stdio example (Airtable)
|
||||
claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \
|
||||
-- npx -y airtable-mcp-server
|
||||
```
|
||||
|
||||
**Option ordering rule:** All flags (`--transport`, `--env`, `--scope`, `--header`) must come **before** the server name. `--` separates the server name from its command.
|
||||
|
||||
### Managing Servers
|
||||
|
||||
```sh
|
||||
claude mcp list # list all configured servers
|
||||
claude mcp get <name> # details for a specific server
|
||||
claude mcp remove <name> # remove a server
|
||||
/mcp # check status inside Claude Code
|
||||
```
|
||||
|
||||
## Configuration Scopes
|
||||
|
||||
| Scope | Loaded in | Shared | Stored in |
|
||||
|-------|-----------|--------|-----------|
|
||||
| `local` (default) | Current project only | No | `~/.claude.json` |
|
||||
| `project` | Current project only | Yes (via `.mcp.json`) | `.mcp.json` in project root |
|
||||
| `user` | All projects | No | `~/.claude.json` |
|
||||
|
||||
```sh
|
||||
claude mcp add --transport http stripe --scope project https://mcp.stripe.com
|
||||
claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic
|
||||
```
|
||||
|
||||
- **Project scope** → checked into version control → team shares same servers
|
||||
- Claude Code prompts for approval before using `.mcp.json` project-scoped servers
|
||||
|
||||
### Environment Variable Expansion in `.mcp.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"api-server": {
|
||||
"type": "http",
|
||||
"url": "${API_BASE_URL:-https://api.example.com}/mcp",
|
||||
"headers": { "Authorization": "Bearer ${API_KEY}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Syntax: `${VAR}` or `${VAR:-default}`. Works in `command`, `args`, `env`, `url`, `headers`.
|
||||
|
||||
## Authentication
|
||||
|
||||
### OAuth 2.0
|
||||
|
||||
Run `/mcp` inside Claude Code to authenticate. Tokens are stored securely and auto-refreshed.
|
||||
|
||||
```sh
|
||||
# Fixed callback port (for pre-registered redirect URIs)
|
||||
claude mcp add --transport http --callback-port 8080 my-server https://mcp.example.com/mcp
|
||||
|
||||
# Pre-configured OAuth credentials
|
||||
claude mcp add --transport http --client-id <id> --client-secret <secret> my-server <url>
|
||||
```
|
||||
|
||||
### Restrict OAuth Scopes
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"slack": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.slack.com/mcp",
|
||||
"oauth": { "scopes": "channels:read chat:write search:read" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Dynamic Headers (non-OAuth auth)
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"internal-api": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.internal.example.com",
|
||||
"headersHelper": "/opt/bin/get-mcp-auth-headers.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Command must output a JSON object of string key-value pairs to stdout
|
||||
- Runs fresh on each connection (10-second timeout, no caching)
|
||||
- Available env vars: `CLAUDE_CODE_MCP_SERVER_NAME`, `CLAUDE_CODE_MCP_SERVER_URL`
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Dynamic Tool Updates & Reconnection
|
||||
|
||||
- MCP `list_changed` notifications → Claude Code auto-refreshes available tools without disconnect
|
||||
- HTTP/SSE servers: auto-reconnect with exponential backoff (5 attempts, starting 1s, doubling each time)
|
||||
- Stdio servers: not auto-reconnected (local processes)
|
||||
|
||||
### Push Messages via Channels
|
||||
|
||||
MCP servers can push messages directly into your session (CI results, alerts, chat). Requires server declaring `claude/channel` capability + `--channels` flag at startup. See [[wiki/claude-code/overview|Claude Code Overview]].
|
||||
|
||||
### Tool Search (context efficiency)
|
||||
|
||||
By default, MCP tools are **deferred** — only names load at session start, definitions fetched on demand.
|
||||
|
||||
| `ENABLE_TOOL_SEARCH` | Behavior |
|
||||
|----------------------|----------|
|
||||
| (unset) | All tools deferred; falls back to upfront for non-Anthropic `ANTHROPIC_BASE_URL` |
|
||||
| `true` | All tools deferred, always |
|
||||
| `auto` | Load upfront if within 10% of context window, defer otherwise |
|
||||
| `auto:<N>` | Custom threshold percentage |
|
||||
| `false` | All tools loaded upfront |
|
||||
|
||||
Requires Sonnet 4+ or Opus 4+. Haiku does not support tool search.
|
||||
|
||||
### MCP Output Limits
|
||||
|
||||
- Warning at 10,000 tokens output
|
||||
- Default max: 25,000 tokens (`MAX_MCP_OUTPUT_TOKENS` env var)
|
||||
- Per-tool override via `_meta["anthropic/maxResultSizeChars"]` in `tools/list` response (max 500,000 chars)
|
||||
|
||||
```sh
|
||||
export MAX_MCP_OUTPUT_TOKENS=50000
|
||||
claude
|
||||
```
|
||||
|
||||
### Claude Code as MCP Server
|
||||
|
||||
```sh
|
||||
claude mcp serve # expose Claude's tools (View, Edit, LS, etc.) to other MCP clients
|
||||
```
|
||||
|
||||
Add to `claude_desktop_config.json`:
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"claude-code": {
|
||||
"type": "stdio",
|
||||
"command": "/full/path/to/claude",
|
||||
"args": ["mcp", "serve"],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Enterprise / Managed MCP
|
||||
|
||||
### Option 1: Exclusive control (`managed-mcp.json`)
|
||||
|
||||
Deploy to system path (requires admin):
|
||||
- macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`
|
||||
- Linux/WSL: `/etc/claude-code/managed-mcp.json`
|
||||
- Windows: `C:\Program Files\ClaudeCode\managed-mcp.json`
|
||||
|
||||
Users cannot add/modify servers. Same format as `.mcp.json`.
|
||||
|
||||
### Option 2: Allowlists / Denylists (policy-based)
|
||||
|
||||
In managed settings:
|
||||
```json
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
{ "serverName": "github" },
|
||||
{ "serverCommand": ["npx", "-y", "approved-package"] },
|
||||
{ "serverUrl": "https://mcp.company.com/*" }
|
||||
],
|
||||
"deniedMcpServers": [
|
||||
{ "serverUrl": "https://*.untrusted.com/*" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- **Denylist takes absolute precedence** over allowlist
|
||||
- Each entry: exactly one of `serverName`, `serverCommand`, or `serverUrl`
|
||||
- Command matching is **exact** (order and all args must match)
|
||||
- URL patterns support `*` wildcards
|
||||
- `allowedMcpServers: []` = complete lockdown (no MCP servers allowed)
|
||||
|
||||
## Popular MCP Servers (Quick Reference)
|
||||
|
||||
| Category | Server | Command |
|
||||
|----------|--------|---------|
|
||||
| Issue tracking | Linear | `claude mcp add --transport http linear https://mcp.linear.app/mcp` |
|
||||
| Issue tracking | Atlassian (Jira/Confluence) | `claude mcp add --transport http atlassian https://mcp.atlassian.com/v1/mcp` |
|
||||
| Version control | GitHub | `claude mcp add --transport http github https://api.githubcopilot.com/mcp/` |
|
||||
| Monitoring | Sentry | `claude mcp add --transport http sentry https://mcp.sentry.dev/mcp` |
|
||||
| Database | Supabase | `claude mcp add --transport http supabase https://mcp.supabase.com/mcp` |
|
||||
| Design | Figma | `claude mcp add --transport http figma-remote-mcp https://mcp.figma.com/mcp` |
|
||||
| Docs/Notes | Notion | `claude mcp add --transport http notion https://mcp.notion.com/mcp` |
|
||||
| Automation | Zapier | `claude mcp add zapier --transport http https://mcp.zapier.com/api/v1/connect` |
|
||||
| Search | Exa | `claude mcp add --transport http exa https://mcp.exa.ai/mcp` |
|
||||
| Communication | Slack | `claude mcp add --transport http --client-id ... --callback-port 3118 slack https://mcp.slack.com/mcp` |
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- **MCP replaces copy-paste**: connect once, Claude reads/acts on the system directly
|
||||
- **HTTP transport is the recommended default** for cloud services; SSE is deprecated
|
||||
- **Three scopes**: local (default, private), project (team-shared via `.mcp.json`), user (cross-project)
|
||||
- **OAuth 2.0** is the standard auth flow; `headersHelper` handles non-OAuth schemes
|
||||
- **Tool search** defers MCP tool definitions to keep context lean — enabled by default on Sonnet 4+
|
||||
- **Channels** let MCP servers push events into your session (webhooks, alerts, chat)
|
||||
- **Enterprise control** via `managed-mcp.json` (exclusive) or allowlist/denylist policies
|
||||
- **Dynamic reconnection** on HTTP/SSE servers; stdio servers must be restarted manually
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Connect Claude Code to tools via MCP.md` (scraped from code.claude.com/docs/en/mcp, 2026-04-17)
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/claude-code/overview|Claude Code Overview]]
|
||||
- [[wiki/agent-sdk/_index|Claude Agent SDK]]
|
||||
- [[wiki/architecture/_index|Architecture Patterns]]
|
||||
139
wiki/claude-code/overview.md
Normal file
139
wiki/claude-code/overview.md
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
---
|
||||
title: "Claude Code Overview"
|
||||
aliases: [claude-code-overview, claude-code-product]
|
||||
tags: [claude-code, anthropic, cli, ai-coding-assistant, agentic]
|
||||
sources: [raw/Claude Code overview.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
# Claude Code Overview
|
||||
|
||||
Claude Code is Anthropic's agentic coding assistant — reads your codebase, edits files, runs commands, and integrates with dev tools across terminal, IDE, desktop, and browser.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
**macOS / Linux / WSL:**
|
||||
```sh
|
||||
curl -fsSL https://claude.ai/install.sh | bash
|
||||
```
|
||||
|
||||
**Windows PowerShell:**
|
||||
```powershell
|
||||
irm https://claude.ai/install.ps1 | iex
|
||||
```
|
||||
|
||||
**Windows CMD:**
|
||||
```bat
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
|
||||
```
|
||||
|
||||
- Native Windows installs require **Git for Windows** first
|
||||
- Native installs auto-update in background
|
||||
- Start in any project: `cd your-project && claude`
|
||||
|
||||
---
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
### Automate tedious tasks
|
||||
- Write tests for untested code
|
||||
- Fix lint errors across a project
|
||||
- Resolve merge conflicts, update dependencies, write release notes
|
||||
|
||||
```sh
|
||||
claude "write tests for the auth module, run them, and fix any failures"
|
||||
```
|
||||
|
||||
### Build features & fix bugs
|
||||
- Describe in plain language → Claude plans, writes across files, verifies
|
||||
- Paste an error message → Claude traces root cause, implements fix
|
||||
|
||||
### Git integration
|
||||
```sh
|
||||
claude "commit my changes with a descriptive message"
|
||||
```
|
||||
- Stages changes, writes commit messages, creates branches, opens PRs
|
||||
- CI automation via GitHub Actions or GitLab CI/CD
|
||||
|
||||
### MCP (Model Context Protocol)
|
||||
- Connect Claude to Google Drive, Jira, Slack, custom tools
|
||||
- Open standard for AI ↔ external data integration
|
||||
- See [[wiki/agent-sdk/overview|Agent SDK Overview]] for programmatic MCP use
|
||||
|
||||
### Customization
|
||||
- **`CLAUDE.md`** — project-root file Claude reads every session; set coding standards, preferred libs, review checklists
|
||||
- **Auto memory** — Claude saves learnings (build commands, debugging insights) across sessions automatically
|
||||
- **Custom commands (skills)** — package repeatable workflows: `/review-pr`, `/deploy-staging`
|
||||
- **Hooks** — shell commands before/after Claude actions (auto-format after edit, lint before commit)
|
||||
|
||||
### Multi-agent & Agent SDK
|
||||
- Spawn multiple Claude Code agents working simultaneously on subtasks
|
||||
- Lead agent coordinates, assigns, and merges results
|
||||
- For fully custom workflows: [[wiki/agent-sdk/overview|Agent SDK]] gives full control over orchestration and tool access
|
||||
|
||||
### CLI scripting & Unix composability
|
||||
```sh
|
||||
# Pipe logs
|
||||
tail -200 app.log | claude -p "Slack me if you see any anomalies"
|
||||
|
||||
# CI translation
|
||||
claude -p "translate new strings into French and raise a PR for review"
|
||||
|
||||
# Security review on changed files
|
||||
git diff main --name-only | claude -p "review these changed files for security issues"
|
||||
```
|
||||
|
||||
### Scheduled / recurring tasks
|
||||
| Option | Where it runs | Use case |
|
||||
|--------|--------------|---------|
|
||||
| Routines | Anthropic-managed infra | Morning PR reviews, overnight CI analysis — runs without your computer |
|
||||
| Desktop scheduled tasks | Local machine | Direct access to local files/tools |
|
||||
| `/loop` | CLI session | Quick polling within a session |
|
||||
|
||||
---
|
||||
|
||||
## Surfaces
|
||||
|
||||
All surfaces share the same CLAUDE.md files, settings, and MCP servers.
|
||||
|
||||
| Surface | Best for |
|
||||
|---------|---------|
|
||||
| Terminal CLI | Full-featured; edit files, run commands |
|
||||
| VS Code / JetBrains | IDE-integrated editing |
|
||||
| Desktop app | Visual diff review, Dispatch task routing |
|
||||
| Web app | Start tasks, continue on mobile |
|
||||
| iOS app + `--teleport` | Mobile continuation of terminal sessions |
|
||||
| Remote Control | Continue local session from any device/phone |
|
||||
| Slack (`@Claude`) | Route bug reports → pull requests from chat |
|
||||
| GitHub Actions / GitLab CI | Automated PR review and issue triage |
|
||||
| Chrome extension | Debug live web applications |
|
||||
| Agent SDK | Build fully custom agents programmatically |
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Claude Code works **across your entire codebase**, not just open files
|
||||
- **`CLAUDE.md`** is the primary way to give Claude persistent project context
|
||||
- **MCP** enables connections to any external data source or tool
|
||||
- **Hooks** automate pre/post actions (format, lint, notify) around Claude's edits
|
||||
- **Routines** run scheduled tasks on Anthropic infrastructure — no local machine needed
|
||||
- All surfaces (CLI, IDE, desktop, web, mobile) share the same underlying engine
|
||||
- The **Agent SDK** is the programmable layer on top of Claude Code for custom automation
|
||||
|
||||
---
|
||||
|
||||
## Related Articles
|
||||
|
||||
- [[wiki/agent-sdk/overview|Agent SDK Overview]] — build custom agents programmatically
|
||||
- [[wiki/agent-sdk/hooks-guide|Hooks Guide]] — all 25 hook events, matchers, exit codes
|
||||
- [[wiki/agent-sdk/agent-skills-plugins|Agent Skills & Plugins]] — loading skills and MCP servers
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Claude Code overview.md` — clipped from code.claude.com/docs/en/overview
|
||||
|
|
@ -5,6 +5,7 @@ Linux terminal customization, shell configs, CLI tool setups, and ricing guides.
|
|||
| Article | Summary | Source | Updated |
|
||||
|---------|---------|--------|---------|
|
||||
| [[wiki/dotfiles/linux-terminal-ricing\|linux-terminal-ricing]] | Full ricing guide: Kitty + Fish + Tide + lsd/bat/fzf/zoxide/lazygit + LazyVim + Kanagawa theme | YouTube — Василий Ломагин | 2026-04-15 |
|
||||
|
||||
|
||||
| [[wiki/dotfiles/terminal-cheatsheet\|terminal-cheatsheet]] | Daily stack reference: WezTerm + fish/zsh, modern CLI (lsd, bat, fd, rg, zoxide, fzf), lazygit, Claude Code, SSH servers | Claude Code session | 2026-04-16 |
|
||||
| [[wiki/dotfiles/terminal-cheatsheet\|terminal-cheatsheet]] | Daily stack reference: WezTerm + fish/zsh, modern CLI (lsd, bat, fd, rg, zoxide, fzf), lazygit, Claude Code, SSH servers | Claude Code session | 2026-04-16 |
|
||||
| [[wiki/dotfiles/wezterm-cli-reference\|wezterm-cli-reference]] | WezTerm CLI subcommands, global options, and scripting patterns | wezterm.org/cli/general.html | 2026-04-17 |
|
||||
| [[wiki/dotfiles/wezterm-colors-appearance\|wezterm-colors-appearance]] | Color schemes, custom palettes, tab bar styling, pane dimming, background images, and opacity | wezterm.org/config/appearance.html | 2026-04-17 |
|
||||
| [[wiki/dotfiles/wezterm-config\|wezterm-config]] | WezTerm Lua config structure, file locations, live reload, CLI overrides, and modular splits | wezterm.org/config/files.html | 2026-04-17 |
|
||||
|
|
|
|||
111
wiki/dotfiles/wezterm-cli-reference.md
Normal file
111
wiki/dotfiles/wezterm-cli-reference.md
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
---
|
||||
title: "WezTerm CLI Reference"
|
||||
aliases: [wezterm-cli, wezterm-command-line]
|
||||
tags: [wezterm, terminal, cli, dotfiles]
|
||||
sources: [raw/CLI Reference - Wez's Terminal Emulator.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
WezTerm ships two executables:
|
||||
|
||||
| Binary | Use case |
|
||||
|--------|----------|
|
||||
| `wezterm` / `wezterm.exe` | Scripting, terminal interaction — use this by default |
|
||||
| `wezterm-gui` / `wezterm-gui.exe` | Launching from a desktop/GUI environment (Windows launchers) |
|
||||
|
||||
> **Windows note:** `wezterm-gui.exe --help` outputs nothing (GUI subsystem has no console). Use `wezterm.exe --help` instead — it delegates to `wezterm-gui` under the covers.
|
||||
|
||||
---
|
||||
|
||||
## Global Options
|
||||
|
||||
```
|
||||
-n, --skip-config Skip loading wezterm.lua
|
||||
--config-file <PATH> Override config file path
|
||||
--config <name=value> Override individual config values at runtime
|
||||
-h, --help
|
||||
-V, --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Subcommands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `start` / `-e` | Start the GUI, optionally running an alternative program |
|
||||
| `ssh` | Establish an SSH session |
|
||||
| `serial` | Open a serial port |
|
||||
| `connect` | Connect to wezterm multiplexer |
|
||||
| `ls-fonts` | Display information about fonts |
|
||||
| `show-keys` | Show current key assignments |
|
||||
| `cli` | Interact with experimental mux server |
|
||||
| `imgcat` | Output an image inline in the terminal |
|
||||
| `set-working-directory` | Emit OSC 7 escape sequence to advise terminal of cwd |
|
||||
| `record` | Record a terminal session as an asciicast |
|
||||
| `replay` | Replay an asciicast terminal session |
|
||||
| `shell-completion` | Generate shell completion scripts |
|
||||
|
||||
---
|
||||
|
||||
## Common Usage Patterns
|
||||
|
||||
```bash
|
||||
# Start wezterm running fish instead of default shell
|
||||
wezterm start -- fish
|
||||
|
||||
# SSH into a host using wezterm's built-in client
|
||||
wezterm ssh user@host
|
||||
|
||||
# Override a single config value without editing wezterm.lua
|
||||
wezterm --config enable_tab_bar=false start
|
||||
|
||||
# Skip config entirely (useful for debugging)
|
||||
wezterm -n start
|
||||
|
||||
# Generate fish completions
|
||||
wezterm shell-completion --shell fish | source
|
||||
|
||||
# List available fonts
|
||||
wezterm ls-fonts
|
||||
|
||||
# Show all key bindings
|
||||
wezterm show-keys
|
||||
|
||||
# Display an image inline
|
||||
wezterm imgcat path/to/image.png
|
||||
|
||||
# Record a session
|
||||
wezterm record output.cast
|
||||
|
||||
# Replay a recorded session
|
||||
wezterm replay output.cast
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Use `wezterm` (not `wezterm-gui`) for scripting — it auto-delegates to the GUI binary when needed
|
||||
- `--config name=value` lets you override any `wezterm.lua` key at runtime without editing the file
|
||||
- `-n` / `--skip-config` is invaluable for debugging config issues
|
||||
- `cli` subcommand exposes the experimental multiplexer server API
|
||||
- `set-working-directory` emits OSC 7 — useful for shell integrations that track cwd in tab titles
|
||||
- `record` / `replay` use asciicast format — compatible with asciinema tooling
|
||||
|
||||
---
|
||||
|
||||
## Related Articles
|
||||
|
||||
- [[wiki/dotfiles/terminal-cheatsheet|Terminal Cheatsheet]] — daily stack reference including WezTerm usage patterns
|
||||
- [[wiki/dotfiles/linux-terminal-ricing|Linux Terminal Ricing]] — full setup guide covering terminal emulator choices
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- [WezTerm CLI Reference](https://wezterm.org/cli/general.html) — official docs
|
||||
- Raw file: `raw/CLI Reference - Wez's Terminal Emulator.md`
|
||||
242
wiki/dotfiles/wezterm-colors-appearance.md
Normal file
242
wiki/dotfiles/wezterm-colors-appearance.md
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
---
|
||||
title: "WezTerm Colors & Appearance"
|
||||
aliases: [wezterm-theming, wezterm-color-scheme, wezterm-appearance]
|
||||
tags: [wezterm, terminal, colors, theming, dotfiles, lua]
|
||||
sources: ["raw/Colors & Appearance - Wez's Terminal Emulator.md"]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
## WezTerm Colors & Appearance
|
||||
|
||||
Full reference for theming WezTerm: color schemes, custom palettes, tab bar styling, pane dimming, background images, and opacity.
|
||||
|
||||
---
|
||||
|
||||
## Color Schemes
|
||||
|
||||
WezTerm ships with 700+ built-in schemes from iTerm2-Color-Schemes, base16, Gogh, and terminal.sexy.
|
||||
|
||||
```lua
|
||||
config.color_scheme = 'Batman'
|
||||
```
|
||||
|
||||
- Browse all schemes: `wezterm.org/colorschemes/index.html`
|
||||
- Auto-switch dark/light based on OS: use `wezterm.gui.get_appearance()`
|
||||
- **Multiplexing note:** when using SSH/TLS domains, the color scheme is controlled by the *server-side* config, not the client
|
||||
|
||||
### Precedence Rules
|
||||
|
||||
1. `color_scheme` (named scheme) takes priority over `colors` section
|
||||
2. Since v20220903: `color_scheme` defines base colors, then `colors` overrides on top
|
||||
3. To merge: use `wezterm.color.get_default_colors()` and manually merge
|
||||
|
||||
---
|
||||
|
||||
## Defining Custom Colors
|
||||
|
||||
```lua
|
||||
config.colors = {
|
||||
foreground = 'silver',
|
||||
background = 'black',
|
||||
|
||||
cursor_bg = '#52ad70',
|
||||
cursor_fg = 'black',
|
||||
cursor_border = '#52ad70',
|
||||
|
||||
selection_fg = 'black',
|
||||
selection_bg = '#fffacd',
|
||||
|
||||
scrollbar_thumb = '#222222',
|
||||
split = '#444444', -- pane split line color
|
||||
|
||||
ansi = { 'black', 'maroon', 'green', 'olive', 'navy', 'purple', 'teal', 'silver' },
|
||||
brights = { 'grey', 'red', 'lime', 'yellow', 'blue', 'fuchsia', 'aqua', 'white' },
|
||||
|
||||
indexed = { [136] = '#af8700' }, -- palette index 16–255
|
||||
|
||||
compose_cursor = 'orange', -- visual cue during IME/dead key input
|
||||
|
||||
-- copy_mode / quick_select
|
||||
copy_mode_active_highlight_bg = { Color = '#000000' },
|
||||
copy_mode_active_highlight_fg = { AnsiColor = 'Black' },
|
||||
copy_mode_inactive_highlight_bg = { Color = '#52ad70' },
|
||||
copy_mode_inactive_highlight_fg = { AnsiColor = 'White' },
|
||||
|
||||
quick_select_label_bg = { Color = 'peru' },
|
||||
quick_select_label_fg = { Color = '#ffffff' },
|
||||
quick_select_match_bg = { AnsiColor = 'Navy' },
|
||||
quick_select_match_fg = { Color = '#ffffff' },
|
||||
}
|
||||
```
|
||||
|
||||
### Color Formats Supported
|
||||
|
||||
- SVG/CSS3 named colors: `'silver'`, `'black'`
|
||||
- Hex: `'#RRGGBB'`
|
||||
- HSL string: `'hsl:235 100 50'`
|
||||
- CSS-style: `rgb(0,255,0)`, `rgba(0,255,0,1)`, `hsl(120,100%,50%)`, `hwb(...)`, `hsv(...)`
|
||||
- Alpha is **only** applied for `selection_fg` / `selection_bg` — ignored elsewhere
|
||||
|
||||
---
|
||||
|
||||
## Inline Color Schemes
|
||||
|
||||
Define named schemes inside `wezterm.lua` — they override all built-ins:
|
||||
|
||||
```lua
|
||||
config.color_scheme = 'Red Scheme'
|
||||
|
||||
config.color_schemes = {
|
||||
['Red Scheme'] = { background = 'red' },
|
||||
['Blue Scheme'] = { background = 'blue' },
|
||||
}
|
||||
```
|
||||
|
||||
Use `wezterm.get_builtin_color_schemes()` for advanced use (random scheme, derive from built-in).
|
||||
|
||||
## External Color Scheme Files
|
||||
|
||||
- Format: TOML with a `[colors]` section
|
||||
- Default location: `~/.config/wezterm/colors/` (POSIX) or `colors/` beside `wezterm.exe` (Windows)
|
||||
- Custom path:
|
||||
|
||||
```lua
|
||||
config.color_scheme_dirs = { '/some/path/to/my/color/schemes' }
|
||||
```
|
||||
|
||||
Files in `color_scheme_dirs` override built-ins.
|
||||
|
||||
---
|
||||
|
||||
## Dynamic Color Changes (Escape Sequences)
|
||||
|
||||
WezTerm supports runtime palette changes via escape sequences. The `dynamic-colors/` directory in iTerm2-Color-Schemes contains ready-made shell scripts:
|
||||
|
||||
```sh
|
||||
bash SomeName.sh # switches color scheme immediately
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tab Bar Appearance
|
||||
|
||||
### Key Options
|
||||
|
||||
| Option | Effect |
|
||||
|--------|--------|
|
||||
| `use_fancy_tab_bar` | `true` = native/fancy (default), `false` = retro |
|
||||
| `enable_tab_bar` | toggle tab bar on/off |
|
||||
| `hide_tab_bar_if_only_one_tab` | auto-hide when single tab |
|
||||
| `tab_bar_at_bottom` | move bar to bottom |
|
||||
| `tab_max_width` | max cell width per tab (retro mode) |
|
||||
|
||||
### Fancy Tab Bar
|
||||
|
||||
```lua
|
||||
config.window_frame = {
|
||||
font = wezterm.font { family = 'Roboto', weight = 'Bold' },
|
||||
font_size = 12.0,
|
||||
active_titlebar_bg = '#333333',
|
||||
inactive_titlebar_bg = '#333333',
|
||||
}
|
||||
config.colors = {
|
||||
tab_bar = { inactive_tab_edge = '#575757' },
|
||||
}
|
||||
```
|
||||
|
||||
### Retro Tab Bar
|
||||
|
||||
```lua
|
||||
config.colors = {
|
||||
tab_bar = {
|
||||
background = '#0b0022',
|
||||
active_tab = { bg_color = '#2b2042', fg_color = '#c0c0c0', intensity = 'Normal' },
|
||||
inactive_tab = { bg_color = '#1b1032', fg_color = '#808080' },
|
||||
inactive_tab_hover = { bg_color = '#3b3052', fg_color = '#909090', italic = true },
|
||||
new_tab = { bg_color = '#1b1032', fg_color = '#808080' },
|
||||
new_tab_hover = { bg_color = '#3b3052', fg_color = '#909090', italic = true },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Inactive Pane Styling
|
||||
|
||||
Inactive panes are dimmed/de-saturated by default. Override with HSB multipliers:
|
||||
|
||||
```lua
|
||||
config.inactive_pane_hsb = {
|
||||
saturation = 0.9, -- < 1.0 = more washed out
|
||||
brightness = 0.8, -- < 1.0 = dimmer
|
||||
}
|
||||
```
|
||||
|
||||
- Values are **multipliers** on existing HSV components (1.0 = no change, 0.5 = half)
|
||||
- Range: 0.0 and up
|
||||
|
||||
---
|
||||
|
||||
## Window Background Image
|
||||
|
||||
```lua
|
||||
config.window_background_image = '/path/to/wallpaper.jpg'
|
||||
|
||||
config.window_background_image_hsb = {
|
||||
brightness = 0.3, -- darken to 1/3
|
||||
hue = 1.0,
|
||||
saturation = 1.0,
|
||||
}
|
||||
```
|
||||
|
||||
- Supported formats: PNG, JPEG, GIF, BMP, ICO, TIFF, PNM, DDS, TGA, farbfeld
|
||||
- Animated GIF/PNG animate while window is focused
|
||||
- Large images increase VRAM usage — resize before use
|
||||
- For tiling/scrolling/repeating control use the `background` config option instead
|
||||
|
||||
---
|
||||
|
||||
## Window Background Gradient
|
||||
|
||||
Available since v20210814. See `window_background_gradient` config option for full syntax.
|
||||
|
||||
---
|
||||
|
||||
## Background & Text Opacity
|
||||
|
||||
```lua
|
||||
config.window_background_opacity = 0.9 -- 0.0 = fully transparent, 1.0 = opaque
|
||||
config.text_background_opacity = 0.3 -- applies to non-default background cells only
|
||||
```
|
||||
|
||||
- Compositing required: macOS, Windows, Wayland — supported out of the box; X11 needs a compositing WM
|
||||
- Non-1.0 opacity impacts render performance
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- **700+ built-in schemes** — set with one line: `config.color_scheme = 'Name'`
|
||||
- **`color_scheme` overrides `colors`** — to override specific colors, either drop `color_scheme` or use `get_default_colors()` to merge
|
||||
- **Color formats** — hex, named, HSL string, and full CSS color syntax all work
|
||||
- **Two tab bar modes** — fancy (native OS look) vs retro; each has distinct color keys
|
||||
- **Inactive panes** — dimmed via `inactive_pane_hsb` HSB multipliers, not absolute values
|
||||
- **Background image HSB** — same multiplier approach as inactive panes
|
||||
- **Opacity** — both window background and text cell background are independently controllable
|
||||
- **Dynamic colors** — escape-sequence driven; use iTerm2-Color-Schemes `dynamic-colors/` scripts for live switching
|
||||
|
||||
---
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/dotfiles/wezterm-cli-reference|WezTerm CLI Reference]]
|
||||
- [[wiki/dotfiles/terminal-cheatsheet|Terminal Cheatsheet]]
|
||||
- [[wiki/dotfiles/linux-terminal-ricing|Linux Terminal Ricing]]
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Colors & Appearance - Wez's Terminal Emulator.md`
|
||||
- Original: https://wezterm.org/config/appearance.html
|
||||
105
wiki/dotfiles/wezterm-config.md
Normal file
105
wiki/dotfiles/wezterm-config.md
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
---
|
||||
title: "WezTerm Configuration Guide"
|
||||
aliases: [wezterm-lua-config, wezterm-setup, wezterm-config-files]
|
||||
tags: [wezterm, terminal, lua, dotfiles, config]
|
||||
sources: [raw/Configuration - Wez's Terminal Emulator.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
WezTerm is configured via a Lua script (`wezterm.lua`). The config system is live-reloading, highly flexible, and supports modular file splits.
|
||||
|
||||
## Config File Locations
|
||||
|
||||
WezTerm searches for config in this priority order:
|
||||
|
||||
1. `$HOME/.wezterm.lua` — recommended starting point
|
||||
2. `$XDG_CONFIG_HOME/wezterm/wezterm.lua` (X11/Wayland)
|
||||
3. `$HOME/.config/wezterm/wezterm.lua` — all other systems
|
||||
4. Same directory as `wezterm.exe` (Windows thumb drive mode — not recommended)
|
||||
|
||||
## Quick Start
|
||||
|
||||
```lua
|
||||
local wezterm = require 'wezterm'
|
||||
local config = wezterm.config_builder()
|
||||
|
||||
config.initial_cols = 120
|
||||
config.initial_rows = 28
|
||||
config.font_size = 10
|
||||
config.color_scheme = 'AdventureTime'
|
||||
|
||||
return config
|
||||
```
|
||||
|
||||
- `wezterm.config_builder()` is the recommended way to build the config table — it provides better error messages than a plain `{}`.
|
||||
|
||||
## Live Reload
|
||||
|
||||
- WezTerm watches the config file and reloads on change automatically
|
||||
- Force reload: `CTRL+SHIFT+R`
|
||||
- **Warning:** the config file can be evaluated multiple times per process (startup + each reload). Avoid side effects in the top-level flow (e.g., spawning background processes unconditionally).
|
||||
|
||||
## CLI Config Overrides
|
||||
|
||||
Override any config key from the command line — these always win over file values, even after reload:
|
||||
|
||||
```bash
|
||||
wezterm --config enable_scroll_bar=true
|
||||
wezterm --config 'exit_behavior="Hold"'
|
||||
```
|
||||
|
||||
Per-window overrides are possible via [`window:set_config_overrides()`](https://wezterm.org/config/lua/window/set_config_overrides.html) in Lua.
|
||||
|
||||
## Modular Config (Multiple Files)
|
||||
|
||||
Break config into Lua modules. `package.path` includes (in order):
|
||||
|
||||
- `~/.config/wezterm/`
|
||||
- `~/.wezterm/`
|
||||
- System Lua paths
|
||||
|
||||
**`~/.config/wezterm/helpers.lua`:**
|
||||
```lua
|
||||
local wezterm = require 'wezterm'
|
||||
local module = {}
|
||||
|
||||
function module.apply_to_config(config)
|
||||
config.color_scheme = 'Batman'
|
||||
end
|
||||
|
||||
return module
|
||||
```
|
||||
|
||||
**`~/.config/wezterm/wezterm.lua`:**
|
||||
```lua
|
||||
local helpers = require 'helpers'
|
||||
local config = {}
|
||||
helpers.apply_to_config(config)
|
||||
return config
|
||||
```
|
||||
|
||||
Convention: modules export an `apply_to_config(config)` function that mutates the config table in place.
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- Config file is Lua — use full language features (functions, modules, conditionals)
|
||||
- Use `wezterm.config_builder()` over raw `{}` for better error output
|
||||
- Default config location: `~/.wezterm.lua` or `~/.config/wezterm/wezterm.lua`
|
||||
- Auto-reloads on file change; `CTRL+SHIFT+R` for manual reload
|
||||
- CLI `--config key=value` overrides always beat file values
|
||||
- Split large configs into modules under `~/.config/wezterm/` using `require`
|
||||
- Avoid side effects at the top level — config is evaluated multiple times
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/dotfiles/wezterm-colors-appearance|WezTerm Colors & Appearance]] — color schemes, tab bar, opacity
|
||||
- [[wiki/dotfiles/wezterm-cli-reference|WezTerm CLI Reference]] — CLI subcommands and scripting
|
||||
- [[wiki/dotfiles/terminal-cheatsheet|Terminal Cheatsheet]] — daily WezTerm + Fish stack reference
|
||||
- [[wiki/dotfiles/linux-terminal-ricing|Linux Terminal Ricing]] — full setup guide with themes
|
||||
|
||||
## Sources
|
||||
|
||||
- `raw/Configuration - Wez's Terminal Emulator.md` (clipped from wezterm.org/config/files.html)
|
||||
7
wiki/llm-models/_index.md
Normal file
7
wiki/llm-models/_index.md
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# LLM Models — Topic Index
|
||||
|
||||
> Reference catalog of language models across providers. Use when selecting a model for a task, comparing capabilities, or checking API availability.
|
||||
|
||||
| Article | Summary | Source | Updated |
|
||||
|---------|---------|--------|---------|
|
||||
| [[wiki/llm-models/openai-model-catalog\|OpenAI Model Catalog]] | All OpenAI API models: GPT-5.x, o-series reasoning, audio/realtime, embeddings, moderation | OpenAI API Docs | 2026-04-17 |
|
||||
159
wiki/llm-models/openai-model-catalog.md
Normal file
159
wiki/llm-models/openai-model-catalog.md
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
---
|
||||
title: "OpenAI Model Catalog"
|
||||
aliases: [openai-models, openai-api-models, gpt-models]
|
||||
tags: [openai, llm, models, api, reference]
|
||||
sources: [raw/All models OpenAI API.md]
|
||||
created: 2026-04-17
|
||||
updated: 2026-04-17
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Complete reference of all models available via the OpenAI API, organized by capability family. Useful when selecting the right model for a task or comparing cost/speed tradeoffs.
|
||||
|
||||
---
|
||||
|
||||
## Flagship / Latest GPT-5 Series
|
||||
|
||||
| Model | Description |
|
||||
|-------|-------------|
|
||||
| GPT-5.3 Chat (`gpt-5.3-chat-latest`) | Instant model used in ChatGPT |
|
||||
| GPT-5.2 (`gpt-5.2`) | Previous frontier model for professional work, configurable reasoning effort |
|
||||
| GPT-5.2 Pro (`gpt-5.2-pro`) | Pro variant — smarter, more precise |
|
||||
| GPT-5.2 Chat (`gpt-5.2-chat-latest`) | GPT-5.2 used in ChatGPT |
|
||||
| GPT-5.1 (`gpt-5.1`) | Best model for coding and agentic tasks, configurable reasoning effort |
|
||||
| GPT-5.1 Chat (`gpt-5.1-chat-latest`) | GPT-5.1 used in ChatGPT |
|
||||
| GPT-5 Chat (`gpt-5-chat-latest`) | GPT-5 used in ChatGPT |
|
||||
|
||||
---
|
||||
|
||||
## Reasoning (o-series)
|
||||
|
||||
| Model | Description | Status |
|
||||
|-------|-------------|--------|
|
||||
| o3 | Complex tasks, succeeded by GPT-5 | Current |
|
||||
| o4-mini | Fast, cost-efficient reasoning, succeeded by GPT-5 mini | Current |
|
||||
| o3-mini | Small alternative to o3 | Current |
|
||||
| o1 | Previous full o-series reasoning model | Legacy |
|
||||
| o1-mini | Small alternative to o1 | Deprecated |
|
||||
| o1-preview | Preview of first o-series model | Deprecated |
|
||||
|
||||
---
|
||||
|
||||
## GPT-4 / GPT-4o Family
|
||||
|
||||
| Model | Description | Status |
|
||||
|-------|-------------|--------|
|
||||
| GPT-4o | Fast, intelligent, flexible | Current |
|
||||
| gpt-4o-mini | Fast, affordable, focused tasks | Current |
|
||||
| gpt-4.1-mini | Smaller, faster GPT-4.1 | Current |
|
||||
| gpt-4.1-nano | Fastest, most cost-efficient GPT-4.1 | Current |
|
||||
| gpt-4.5-preview | Large model | Deprecated |
|
||||
| gpt-4-turbo | Older high-intelligence model | Legacy |
|
||||
| gpt-4-turbo-preview | Older fast model | Deprecated |
|
||||
| GPT-4 | Older high-intelligence model | Legacy |
|
||||
| chatgpt-4o-latest | GPT-4o used in ChatGPT | Deprecated |
|
||||
|
||||
---
|
||||
|
||||
## Realtime & Audio
|
||||
|
||||
| Model | Description |
|
||||
|-------|-------------|
|
||||
| gpt-realtime-1.5 | Best voice model — audio in, audio out |
|
||||
| gpt-realtime | Realtime text and audio I/O |
|
||||
| gpt-realtime-mini | Cost-efficient realtime |
|
||||
| gpt-audio-1.5 | Best voice model with Chat Completions API |
|
||||
| gpt-audio | Audio I/O via Chat Completions |
|
||||
| gpt-audio-mini | Cost-efficient audio |
|
||||
| gpt-4o-audio-preview | GPT-4o audio I/O |
|
||||
| gpt-4o-mini-audio-preview | Smaller audio I/O |
|
||||
| gpt-4o-realtime-preview | GPT-4o realtime text + audio |
|
||||
| gpt-4o-mini-realtime-preview | Smaller realtime model |
|
||||
|
||||
## Transcription & TTS
|
||||
|
||||
| Model | Description |
|
||||
|-------|-------------|
|
||||
| gpt-4o-transcribe | Speech-to-text (GPT-4o powered) |
|
||||
| gpt-4o-mini-transcribe | Speech-to-text (GPT-4o mini) |
|
||||
| gpt-4o-transcribe-diarize | Transcription with speaker identification |
|
||||
| gpt-4o-mini-tts | Text-to-speech (GPT-4o mini) |
|
||||
| TTS-1 | Text-to-speech, optimized for speed |
|
||||
| TTS-1 HD | Text-to-speech, optimized for quality |
|
||||
| Whisper | General-purpose speech recognition |
|
||||
|
||||
---
|
||||
|
||||
## Search Models
|
||||
|
||||
| Model | Description |
|
||||
|-------|-------------|
|
||||
| gpt-4o-search-preview | GPT-4o with web search (Chat Completions) |
|
||||
| gpt-4o-mini-search-preview | Fast, affordable web search |
|
||||
|
||||
---
|
||||
|
||||
## Specialized
|
||||
|
||||
| Model | Description |
|
||||
|-------|-------------|
|
||||
| computer-use-preview | Specialized for computer-use tool |
|
||||
|
||||
---
|
||||
|
||||
## Embedding Models
|
||||
|
||||
| Model | Description | Status |
|
||||
|-------|-------------|--------|
|
||||
| text-embedding-3-large | Most capable embedding model | Current |
|
||||
| text-embedding-3-small | Smaller, fast embedding model | Current |
|
||||
| text-embedding-ada-002 | Older embedding model | Legacy |
|
||||
|
||||
---
|
||||
|
||||
## Moderation Models
|
||||
|
||||
| Model | Description | Status |
|
||||
|-------|-------------|--------|
|
||||
| omni-moderation-latest | Text + image harmful content detection | Current |
|
||||
| text-moderation-latest | Text-only moderation | Deprecated |
|
||||
| text-moderation-stable | Text-only moderation stable | Deprecated |
|
||||
|
||||
---
|
||||
|
||||
## Legacy / Deprecated Base Models
|
||||
|
||||
| Model | Notes |
|
||||
|-------|-------|
|
||||
| gpt-3.5-turbo | Legacy chat + non-chat |
|
||||
| babbage-002 | Replacement for GPT-3 ada/babbage base |
|
||||
| davinci-002 | Replacement for GPT-3 curie/davinci base |
|
||||
|
||||
---
|
||||
|
||||
## Key Takeaways
|
||||
|
||||
- **GPT-5.x** is the current frontier series; GPT-5.1 is best for coding/agentic work
|
||||
- **o-series** (o3, o4-mini) are reasoning models for complex tasks — succeeded by GPT-5
|
||||
- **Realtime/Audio** has its own dedicated model family separate from Chat Completions
|
||||
- **Diarization** (speaker identification) is a distinct model: `gpt-4o-transcribe-diarize`
|
||||
- **Embedding**: prefer `text-embedding-3-large` for accuracy, `text-embedding-3-small` for cost
|
||||
- **Moderation**: use `omni-moderation-latest` — handles both text and images
|
||||
- **computer-use-preview** is the specialized model for agentic computer control
|
||||
- Many older models (o1-mini, gpt-4.5-preview, chatgpt-4o-latest) are now deprecated — avoid in new projects
|
||||
|
||||
---
|
||||
|
||||
## Related
|
||||
|
||||
- [[wiki/tech-patterns/_index|Tech Patterns — AI stack]]
|
||||
- [[wiki/agent-sdk/_index|Claude Agent SDK]]
|
||||
- [[wiki/architecture/_index|Multi-agent AI architecture]]
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- OpenAI API Docs: All Models page (clipped 2026-04-17)
|
||||
- Raw source: `raw/All models OpenAI API.md`
|
||||
Loading…
Add table
Reference in a new issue