Initial commit: Discord-Claude Gateway with event-driven agent runtime
This commit is contained in:
568
references/claude code/agent-sdk.md
Normal file
568
references/claude code/agent-sdk.md
Normal file
@@ -0,0 +1,568 @@
|
||||
# Agent SDK overview
|
||||
|
||||
Build production AI agents with Claude Code as a library
|
||||
|
||||
---
|
||||
|
||||
<Note>
|
||||
The Claude Code SDK has been renamed to the Claude Agent SDK. If you're migrating from the old SDK, see the [Migration Guide](/docs/en/agent-sdk/migration-guide).
|
||||
</Note>
|
||||
|
||||
Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="Find and fix the bug in auth.py",
|
||||
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
|
||||
):
|
||||
print(message) # Claude reads the file, finds the bug, edits it
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Find and fix the bug in auth.py",
|
||||
options: { allowedTools: ["Read", "Edit", "Bash"] }
|
||||
})) {
|
||||
console.log(message); // Claude reads the file, finds the bug, edits it
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
The Agent SDK includes built-in tools for reading files, running commands, and editing code, so your agent can start working immediately without you implementing tool execution. Dive into the quickstart or explore real agents built with the SDK:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quickstart" icon="play" href="/docs/en/agent-sdk/quickstart">
|
||||
Build a bug-fixing agent in minutes
|
||||
</Card>
|
||||
<Card title="Example agents" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">
|
||||
Email assistant, research agent, and more
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Get started
|
||||
|
||||
<Steps>
|
||||
<Step title="Install the SDK">
|
||||
<Tabs>
|
||||
<Tab title="TypeScript">
|
||||
```bash
|
||||
npm install @anthropic-ai/claude-agent-sdk
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Python">
|
||||
```bash
|
||||
pip install claude-agent-sdk
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
<Step title="Set your API key">
|
||||
Get an API key from the [Console](https://platform.claude.com/), then set it as an environment variable:
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
The SDK also supports authentication via third-party API providers:
|
||||
|
||||
- **Amazon Bedrock**: set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials
|
||||
- **Google Vertex AI**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials
|
||||
- **Microsoft Azure**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials
|
||||
|
||||
See the setup guides for [Bedrock](https://code.claude.com/docs/en/amazon-bedrock), [Vertex AI](https://code.claude.com/docs/en/google-vertex-ai), or [Azure AI Foundry](https://code.claude.com/docs/en/azure-ai-foundry) for details.
|
||||
|
||||
<Note>
|
||||
Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.
|
||||
</Note>
|
||||
</Step>
|
||||
<Step title="Run your first agent">
|
||||
This example creates an agent that lists files in your current directory using built-in tools.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="What files are in this directory?",
|
||||
options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "What files are in this directory?",
|
||||
options: { allowedTools: ["Bash", "Glob"] }
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
**Ready to build?** Follow the [Quickstart](/docs/en/agent-sdk/quickstart) to create an agent that finds and fixes bugs in minutes.
|
||||
|
||||
## Capabilities
|
||||
|
||||
Everything that makes Claude Code powerful is available in the SDK:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Built-in tools">
|
||||
Your agent can read files, run commands, and search codebases out of the box. Key tools include:
|
||||
|
||||
| Tool | What it does |
|
||||
|------|--------------|
|
||||
| **Read** | Read any file in the working directory |
|
||||
| **Write** | Create new files |
|
||||
| **Edit** | Make precise edits to existing files |
|
||||
| **Bash** | Run terminal commands, scripts, git operations |
|
||||
| **Glob** | Find files by pattern (`**/*.ts`, `src/**/*.py`) |
|
||||
| **Grep** | Search file contents with regex |
|
||||
| **WebSearch** | Search the web for current information |
|
||||
| **WebFetch** | Fetch and parse web page content |
|
||||
| **[AskUserQuestion](/docs/en/agent-sdk/user-input#handle-clarifying-questions)** | Ask the user clarifying questions with multiple choice options |
|
||||
|
||||
This example creates an agent that searches your codebase for TODO comments:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="Find all TODO comments and create a summary",
|
||||
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Find all TODO comments and create a summary",
|
||||
options: { allowedTools: ["Read", "Glob", "Grep"] }
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
</Tab>
|
||||
<Tab title="Hooks">
|
||||
Run custom code at key points in the agent lifecycle. SDK hooks use callback functions to validate, log, block, or transform agent behavior.
|
||||
|
||||
**Available hooks:** `PreToolUse`, `PostToolUse`, `Stop`, `SessionStart`, `SessionEnd`, `UserPromptSubmit`, and more.
|
||||
|
||||
This example logs all file changes to an audit file:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
|
||||
|
||||
|
||||
async def log_file_change(input_data, tool_use_id, context):
|
||||
file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
|
||||
with open("./audit.log", "a") as f:
|
||||
f.write(f"{datetime.now()}: modified {file_path}\n")
|
||||
return {}
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="Refactor utils.py to improve readability",
|
||||
options=ClaudeAgentOptions(
|
||||
permission_mode="acceptEdits",
|
||||
hooks={
|
||||
"PostToolUse": [
|
||||
HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
|
||||
]
|
||||
},
|
||||
),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { appendFile } from "fs/promises";
|
||||
|
||||
const logFileChange: HookCallback = async (input) => {
|
||||
const filePath = (input as any).tool_input?.file_path ?? "unknown";
|
||||
await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);
|
||||
return {};
|
||||
};
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Refactor utils.py to improve readability",
|
||||
options: {
|
||||
permissionMode: "acceptEdits",
|
||||
hooks: {
|
||||
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
|
||||
}
|
||||
}
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
[Learn more about hooks →](/docs/en/agent-sdk/hooks)
|
||||
</Tab>
|
||||
<Tab title="Subagents">
|
||||
Spawn specialized agents to handle focused subtasks. Your main agent delegates work, and subagents report back with results.
|
||||
|
||||
Define custom agents with specialized instructions. Include `Task` in `allowedTools` since subagents are invoked via the Task tool:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="Use the code-reviewer agent to review this codebase",
|
||||
options=ClaudeAgentOptions(
|
||||
allowed_tools=["Read", "Glob", "Grep", "Task"],
|
||||
agents={
|
||||
"code-reviewer": AgentDefinition(
|
||||
description="Expert code reviewer for quality and security reviews.",
|
||||
prompt="Analyze code quality and suggest improvements.",
|
||||
tools=["Read", "Glob", "Grep"],
|
||||
)
|
||||
},
|
||||
),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Use the code-reviewer agent to review this codebase",
|
||||
options: {
|
||||
allowedTools: ["Read", "Glob", "Grep", "Task"],
|
||||
agents: {
|
||||
"code-reviewer": {
|
||||
description: "Expert code reviewer for quality and security reviews.",
|
||||
prompt: "Analyze code quality and suggest improvements.",
|
||||
tools: ["Read", "Glob", "Grep"]
|
||||
}
|
||||
}
|
||||
}
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Messages from within a subagent's context include a `parent_tool_use_id` field, letting you track which messages belong to which subagent execution.
|
||||
|
||||
[Learn more about subagents →](/docs/en/agent-sdk/subagents)
|
||||
</Tab>
|
||||
<Tab title="MCP">
|
||||
Connect to external systems via the Model Context Protocol: databases, browsers, APIs, and [hundreds more](https://github.com/modelcontextprotocol/servers).
|
||||
|
||||
This example connects the [Playwright MCP server](https://github.com/microsoft/playwright-mcp) to give your agent browser automation capabilities:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="Open example.com and describe what you see",
|
||||
options=ClaudeAgentOptions(
|
||||
mcp_servers={
|
||||
"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
|
||||
}
|
||||
),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Open example.com and describe what you see",
|
||||
options: {
|
||||
mcpServers: {
|
||||
playwright: { command: "npx", args: ["@playwright/mcp@latest"] }
|
||||
}
|
||||
}
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
[Learn more about MCP →](/docs/en/agent-sdk/mcp)
|
||||
</Tab>
|
||||
<Tab title="Permissions">
|
||||
Control exactly which tools your agent can use. Allow safe operations, block dangerous ones, or require approval for sensitive actions.
|
||||
|
||||
<Note>
|
||||
For interactive approval prompts and the `AskUserQuestion` tool, see [Handle approvals and user input](/docs/en/agent-sdk/user-input).
|
||||
</Note>
|
||||
|
||||
This example creates a read-only agent that can analyze but not modify code:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
|
||||
async def main():
|
||||
async for message in query(
|
||||
prompt="Review this code for best practices",
|
||||
options=ClaudeAgentOptions(
|
||||
allowed_tools=["Read", "Glob", "Grep"], permission_mode="bypassPermissions"
|
||||
),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
for await (const message of query({
|
||||
prompt: "Review this code for best practices",
|
||||
options: {
|
||||
allowedTools: ["Read", "Glob", "Grep"],
|
||||
permissionMode: "bypassPermissions"
|
||||
}
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
[Learn more about permissions →](/docs/en/agent-sdk/permissions)
|
||||
</Tab>
|
||||
<Tab title="Sessions">
|
||||
Maintain context across multiple exchanges. Claude remembers files read, analysis done, and conversation history. Resume sessions later, or fork them to explore different approaches.
|
||||
|
||||
This example captures the session ID from the first query, then resumes to continue with full context:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import asyncio
|
||||
from claude_agent_sdk import query, ClaudeAgentOptions
|
||||
|
||||
|
||||
async def main():
|
||||
session_id = None
|
||||
|
||||
# First query: capture the session ID
|
||||
async for message in query(
|
||||
prompt="Read the authentication module",
|
||||
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
|
||||
):
|
||||
if hasattr(message, "subtype") and message.subtype == "init":
|
||||
session_id = message.session_id
|
||||
|
||||
# Resume with full context from the first query
|
||||
async for message in query(
|
||||
prompt="Now find all places that call it", # "it" = auth module
|
||||
options=ClaudeAgentOptions(resume=session_id),
|
||||
):
|
||||
if hasattr(message, "result"):
|
||||
print(message.result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
let sessionId: string | undefined;
|
||||
|
||||
// First query: capture the session ID
|
||||
for await (const message of query({
|
||||
prompt: "Read the authentication module",
|
||||
options: { allowedTools: ["Read", "Glob"] }
|
||||
})) {
|
||||
if (message.type === "system" && message.subtype === "init") {
|
||||
sessionId = message.session_id;
|
||||
}
|
||||
}
|
||||
|
||||
// Resume with full context from the first query
|
||||
for await (const message of query({
|
||||
prompt: "Now find all places that call it", // "it" = auth module
|
||||
options: { resume: sessionId }
|
||||
})) {
|
||||
if ("result" in message) console.log(message.result);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
[Learn more about sessions →](/docs/en/agent-sdk/sessions)
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Claude Code features
|
||||
|
||||
The SDK also supports Claude Code's filesystem-based configuration. To use these features, set `setting_sources=["project"]` (Python) or `settingSources: ['project']` (TypeScript) in your options.
|
||||
|
||||
| Feature | Description | Location |
|
||||
|---------|-------------|----------|
|
||||
| [Skills](/docs/en/agent-sdk/skills) | Specialized capabilities defined in Markdown | `.claude/skills/SKILL.md` |
|
||||
| [Slash commands](/docs/en/agent-sdk/slash-commands) | Custom commands for common tasks | `.claude/commands/*.md` |
|
||||
| [Memory](/docs/en/agent-sdk/modifying-system-prompts) | Project context and instructions | `CLAUDE.md` or `.claude/CLAUDE.md` |
|
||||
| [Plugins](/docs/en/agent-sdk/plugins) | Extend with custom commands, agents, and MCP servers | Programmatic via `plugins` option |
|
||||
|
||||
## Compare the Agent SDK to other Claude tools
|
||||
|
||||
The Claude platform offers multiple ways to build with Claude. Here's how the Agent SDK fits in:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Agent SDK vs Client SDK">
|
||||
The [Anthropic Client SDK](/docs/en/api/client-sdks) gives you direct API access: you send prompts and implement tool execution yourself. The **Agent SDK** gives you Claude with built-in tool execution.
|
||||
|
||||
With the Client SDK, you implement a tool loop. With the Agent SDK, Claude handles it:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
# Client SDK: You implement the tool loop
|
||||
response = client.messages.create(...)
|
||||
while response.stop_reason == "tool_use":
|
||||
result = your_tool_executor(response.tool_use)
|
||||
response = client.messages.create(tool_result=result, **params)
|
||||
|
||||
# Agent SDK: Claude handles tools autonomously
|
||||
async for message in query(prompt="Fix the bug in auth.py"):
|
||||
print(message)
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
// Client SDK: You implement the tool loop
|
||||
let response = await client.messages.create({ ...params });
|
||||
while (response.stop_reason === "tool_use") {
|
||||
const result = yourToolExecutor(response.tool_use);
|
||||
response = await client.messages.create({ tool_result: result, ...params });
|
||||
}
|
||||
|
||||
// Agent SDK: Claude handles tools autonomously
|
||||
for await (const message of query({ prompt: "Fix the bug in auth.py" })) {
|
||||
console.log(message);
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="Agent SDK vs Claude Code CLI">
|
||||
Same capabilities, different interface:
|
||||
|
||||
| Use case | Best choice |
|
||||
|----------|-------------|
|
||||
| Interactive development | CLI |
|
||||
| CI/CD pipelines | SDK |
|
||||
| Custom applications | SDK |
|
||||
| One-off tasks | CLI |
|
||||
| Production automation | SDK |
|
||||
|
||||
Many teams use both: CLI for daily development, SDK for production. Workflows translate directly between them.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Changelog
|
||||
|
||||
View the full changelog for SDK updates, bug fixes, and new features:
|
||||
|
||||
- **TypeScript SDK**: [view CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)
|
||||
- **Python SDK**: [view CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md)
|
||||
|
||||
## Reporting bugs
|
||||
|
||||
If you encounter bugs or issues with the Agent SDK:
|
||||
|
||||
- **TypeScript SDK**: [report issues on GitHub](https://github.com/anthropics/claude-agent-sdk-typescript/issues)
|
||||
- **Python SDK**: [report issues on GitHub](https://github.com/anthropics/claude-agent-sdk-python/issues)
|
||||
|
||||
## Branding guidelines
|
||||
|
||||
For partners integrating the Claude Agent SDK, use of Claude branding is optional. When referencing Claude in your product:
|
||||
|
||||
**Allowed:**
|
||||
- "Claude Agent" (preferred for dropdown menus)
|
||||
- "Claude" (when within a menu already labeled "Agents")
|
||||
- "{YourAgentName} Powered by Claude" (if you have an existing agent name)
|
||||
|
||||
**Not permitted:**
|
||||
- "Claude Code" or "Claude Code Agent"
|
||||
- Claude Code-branded ASCII art or visual elements that mimic Claude Code
|
||||
|
||||
Your product should maintain its own branding and not appear to be Claude Code or any Anthropic product. For questions about branding compliance, contact our [sales team](https://www.anthropic.com/contact-sales).
|
||||
|
||||
## License and terms
|
||||
|
||||
Use of the Claude Agent SDK is governed by [Anthropic's Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms), including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component's LICENSE file.
|
||||
|
||||
## Next steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quickstart" icon="play" href="/docs/en/agent-sdk/quickstart">
|
||||
Build an agent that finds and fixes bugs in minutes
|
||||
</Card>
|
||||
<Card title="Example agents" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">
|
||||
Email assistant, research agent, and more
|
||||
</Card>
|
||||
<Card title="TypeScript SDK" icon="code" href="/docs/en/agent-sdk/typescript">
|
||||
Full TypeScript API reference and examples
|
||||
</Card>
|
||||
<Card title="Python SDK" icon="code" href="/docs/en/agent-sdk/python">
|
||||
Full Python API reference and examples
|
||||
</Card>
|
||||
</CardGroup>
|
||||
163
references/claude code/claude-cli.md
Normal file
163
references/claude code/claude-cli.md
Normal file
@@ -0,0 +1,163 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# CLI reference
|
||||
|
||||
> Complete reference for Claude Code command-line interface, including commands and flags.
|
||||
|
||||
## CLI commands
|
||||
|
||||
| Command | Description | Example |
|
||||
| :------------------------------ | :----------------------------------------------------------------- | :------------------------------------------------ |
|
||||
| `claude` | Start interactive REPL | `claude` |
|
||||
| `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` |
|
||||
| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |
|
||||
| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |
|
||||
| `claude -c` | Continue most recent conversation in current directory | `claude -c` |
|
||||
| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |
|
||||
| `claude -r "<session>" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` |
|
||||
| `claude update` | Update to latest version | `claude update` |
|
||||
| `claude agents` | List all configured [subagents](/en/sub-agents), grouped by source | `claude agents` |
|
||||
| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](/en/mcp). |
|
||||
|
||||
## CLI flags
|
||||
|
||||
Customize Claude Code's behavior with these command-line flags:
|
||||
|
||||
| Flag | Description | Example |
|
||||
| :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |
|
||||
| `--add-dir` | Add additional working directories for Claude to access (validates each path exists as a directory) | `claude --add-dir ../apps ../lib` |
|
||||
| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |
|
||||
| `--agents` | Define custom [subagents](/en/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |
|
||||
| `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |
|
||||
| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"` |
|
||||
| `--append-system-prompt` | Append custom text to the end of the default system prompt (works in both interactive and print modes) | `claude --append-system-prompt "Always use TypeScript"` |
|
||||
| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt (print mode only) | `claude -p --append-system-prompt-file ./extra-rules.txt "query"` |
|
||||
| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |
|
||||
| `--chrome` | Enable [Chrome browser integration](/en/chrome) for web automation and testing | `claude --chrome` |
|
||||
| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` |
|
||||
| `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` |
|
||||
| `--debug` | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`) | `claude --debug "api,mcp"` |
|
||||
| `--disable-slash-commands` | Disable all skills and slash commands for this session | `claude --disable-slash-commands` |
|
||||
| `--disallowedTools` | Tools that are removed from the model's context and cannot be used | `"Bash(git log *)" "Bash(git diff *)" "Edit"` |
|
||||
| `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` |
|
||||
| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |
|
||||
| `--from-pr` | Resume sessions linked to a specific GitHub PR. Accepts a PR number or URL. Sessions are automatically linked when created via `gh pr create` | `claude --from-pr 123` |
|
||||
| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` |
|
||||
| `--init` | Run initialization hooks and start interactive mode | `claude --init` |
|
||||
| `--init-only` | Run initialization hooks and exit (no interactive session) | `claude --init-only` |
|
||||
| `--include-partial-messages` | Include partial streaming events in output (requires `--print` and `--output-format=stream-json`) | `claude -p --output-format stream-json --include-partial-messages "query"` |
|
||||
| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |
|
||||
| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](https://platform.claude.com/docs/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |
|
||||
| `--maintenance` | Run maintenance hooks and exit | `claude --maintenance` |
|
||||
| `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` |
|
||||
| `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default | `claude -p --max-turns 3 "query"` |
|
||||
| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` |
|
||||
| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name | `claude --model claude-sonnet-4-6` |
|
||||
| `--no-chrome` | Disable [Chrome browser integration](/en/chrome) for this session | `claude --no-chrome` |
|
||||
| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only) | `claude -p --no-session-persistence "query"` |
|
||||
| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |
|
||||
| `--permission-mode` | Begin in a specified [permission mode](/en/permissions#permission-modes) | `claude --permission-mode plan` |
|
||||
| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |
|
||||
| `--plugin-dir` | Load plugins from directories for this session only (repeatable) | `claude --plugin-dir ./my-plugins` |
|
||||
| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |
|
||||
| `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |
|
||||
| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` |
|
||||
| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |
|
||||
| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` |
|
||||
| `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.json` |
|
||||
| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` |
|
||||
| `--system-prompt` | Replace the entire system prompt with custom text (works in both interactive and print modes) | `claude --system-prompt "You are a Python expert"` |
|
||||
| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt (print mode only) | `claude -p --system-prompt-file ./custom-prompt.txt "query"` |
|
||||
| `--teleport` | Resume a [web session](/en/claude-code-on-the-web) in your local terminal | `claude --teleport` |
|
||||
| `--teammate-mode` | Set how [agent team](/en/agent-teams) teammates display: `auto` (default), `in-process`, or `tmux`. See [set up agent teams](/en/agent-teams#set-up-agent-teams) | `claude --teammate-mode in-process` |
|
||||
| `--tools` | Restrict which built-in tools Claude can use (works in both interactive and print modes). Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |
|
||||
| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |
|
||||
| `--version`, `-v` | Output the version number | `claude -v` |
|
||||
| `--worktree`, `-w` | Start Claude in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) at `<repo>/.claude/worktrees/<name>`. If no name is given, one is auto-generated | `claude -w feature-auth` |
|
||||
|
||||
<Tip>
|
||||
The `--output-format json` flag is particularly useful for scripting and
|
||||
automation, allowing you to parse Claude's responses programmatically.
|
||||
</Tip>
|
||||
|
||||
### Agents flag format
|
||||
|
||||
The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields:
|
||||
|
||||
| Field | Required | Description |
|
||||
| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `description` | Yes | Natural language description of when the subagent should be invoked |
|
||||
| `prompt` | Yes | The system prompt that guides the subagent's behavior |
|
||||
| `tools` | No | Array of specific tools the subagent can use, for example `["Read", "Edit", "Bash"]`. If omitted, inherits all tools. Supports [`Task(agent_type)`](/en/sub-agents#restrict-which-subagents-can-be-spawned) syntax |
|
||||
| `disallowedTools` | No | Array of tool names to explicitly deny for this subagent |
|
||||
| `model` | No | Model alias to use: `sonnet`, `opus`, `haiku`, or `inherit`. If omitted, defaults to `inherit` |
|
||||
| `skills` | No | Array of [skill](/en/skills) names to preload into the subagent's context |
|
||||
| `mcpServers` | No | Array of [MCP servers](/en/mcp) for this subagent. Each entry is a server name string or a `{name: config}` object |
|
||||
| `maxTurns` | No | Maximum number of agentic turns before the subagent stops |
|
||||
|
||||
Example:
|
||||
|
||||
```bash theme={null}
|
||||
claude --agents '{
|
||||
"code-reviewer": {
|
||||
"description": "Expert code reviewer. Use proactively after code changes.",
|
||||
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
|
||||
"tools": ["Read", "Grep", "Glob", "Bash"],
|
||||
"model": "sonnet"
|
||||
},
|
||||
"debugger": {
|
||||
"description": "Debugging specialist for errors and test failures.",
|
||||
"prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
For more details on creating and using subagents, see the [subagents documentation](/en/sub-agents).
|
||||
|
||||
### System prompt flags
|
||||
|
||||
Claude Code provides four flags for customizing the system prompt, each serving a different purpose:
|
||||
|
||||
| Flag | Behavior | Modes | Use Case |
|
||||
| :---------------------------- | :------------------------------------------ | :------------------ | :------------------------------------------------------------------- |
|
||||
| `--system-prompt` | **Replaces** entire default prompt | Interactive + Print | Complete control over Claude's behavior and instructions |
|
||||
| `--system-prompt-file` | **Replaces** with file contents | Print only | Load prompts from files for reproducibility and version control |
|
||||
| `--append-system-prompt` | **Appends** to default prompt | Interactive + Print | Add specific instructions while keeping default Claude Code behavior |
|
||||
| `--append-system-prompt-file` | **Appends** file contents to default prompt | Print only | Load additional instructions from files while keeping defaults |
|
||||
|
||||
**When to use each:**
|
||||
|
||||
* **`--system-prompt`**: Use when you need complete control over Claude's system prompt. This removes all default Claude Code instructions, giving you a blank slate.
|
||||
```bash theme={null}
|
||||
claude --system-prompt "You are a Python expert who only writes type-annotated code"
|
||||
```
|
||||
|
||||
* **`--system-prompt-file`**: Use when you want to load a custom prompt from a file, useful for team consistency or version-controlled prompt templates.
|
||||
```bash theme={null}
|
||||
claude -p --system-prompt-file ./prompts/code-review.txt "Review this PR"
|
||||
```
|
||||
|
||||
* **`--append-system-prompt`**: Use when you want to add specific instructions while keeping Claude Code's default capabilities intact. This is the safest option for most use cases.
|
||||
```bash theme={null}
|
||||
claude --append-system-prompt "Always use TypeScript and include JSDoc comments"
|
||||
```
|
||||
|
||||
* **`--append-system-prompt-file`**: Use when you want to append instructions from a file while keeping Claude Code's defaults. Useful for version-controlled additions.
|
||||
```bash theme={null}
|
||||
claude -p --append-system-prompt-file ./prompts/style-rules.txt "Review this PR"
|
||||
```
|
||||
|
||||
`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag.
|
||||
|
||||
For most use cases, `--append-system-prompt` or `--append-system-prompt-file` is recommended as they preserve Claude Code's built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt.
|
||||
|
||||
## See also
|
||||
|
||||
* [Chrome extension](/en/chrome) - Browser automation and web testing
|
||||
* [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features
|
||||
* [Quickstart guide](/en/quickstart) - Getting started with Claude Code
|
||||
* [Common workflows](/en/common-workflows) - Advanced workflows and patterns
|
||||
* [Settings](/en/settings) - Configuration options
|
||||
* [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) - Programmatic usage and integrations
|
||||
1744
references/claude code/hooks-reference.md
Normal file
1744
references/claude code/hooks-reference.md
Normal file
File diff suppressed because it is too large
Load Diff
714
references/claude code/plugins-reference.md
Normal file
714
references/claude code/plugins-reference.md
Normal file
@@ -0,0 +1,714 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Plugins reference
|
||||
|
||||
> Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications.
|
||||
|
||||
<Tip>
|
||||
Looking to install plugins? See [Discover and install plugins](/en/discover-plugins). For creating plugins, see [Plugins](/en/plugins). For distributing plugins, see [Plugin marketplaces](/en/plugin-marketplaces).
|
||||
</Tip>
|
||||
|
||||
This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.
|
||||
|
||||
A **plugin** is a self-contained directory of components that extends Claude Code with custom functionality. Plugin components include skills, agents, hooks, MCP servers, and LSP servers.
|
||||
|
||||
## Plugin components reference
|
||||
|
||||
### Skills
|
||||
|
||||
Plugins add skills to Claude Code, creating `/name` shortcuts that you or Claude can invoke.
|
||||
|
||||
**Location**: `skills/` or `commands/` directory in plugin root
|
||||
|
||||
**File format**: Skills are directories with `SKILL.md`; commands are simple markdown files
|
||||
|
||||
**Skill structure**:
|
||||
|
||||
```
|
||||
skills/
|
||||
├── pdf-processor/
|
||||
│ ├── SKILL.md
|
||||
│ ├── reference.md (optional)
|
||||
│ └── scripts/ (optional)
|
||||
└── code-reviewer/
|
||||
└── SKILL.md
|
||||
```
|
||||
|
||||
**Integration behavior**:
|
||||
|
||||
* Skills and commands are automatically discovered when the plugin is installed
|
||||
* Claude can invoke them automatically based on task context
|
||||
* Skills can include supporting files alongside SKILL.md
|
||||
|
||||
For complete details, see [Skills](/en/skills).
|
||||
|
||||
### Agents
|
||||
|
||||
Plugins can provide specialized subagents for specific tasks that Claude can invoke automatically when appropriate.
|
||||
|
||||
**Location**: `agents/` directory in plugin root
|
||||
|
||||
**File format**: Markdown files describing agent capabilities
|
||||
|
||||
**Agent structure**:
|
||||
|
||||
```markdown theme={null}
|
||||
---
|
||||
name: agent-name
|
||||
description: What this agent specializes in and when Claude should invoke it
|
||||
---
|
||||
|
||||
Detailed system prompt for the agent describing its role, expertise, and behavior.
|
||||
```
|
||||
|
||||
**Integration points**:
|
||||
|
||||
* Agents appear in the `/agents` interface
|
||||
* Claude can invoke agents automatically based on task context
|
||||
* Agents can be invoked manually by users
|
||||
* Plugin agents work alongside built-in Claude agents
|
||||
|
||||
For complete details, see [Subagents](/en/sub-agents).
|
||||
|
||||
### Hooks
|
||||
|
||||
Plugins can provide event handlers that respond to Claude Code events automatically.
|
||||
|
||||
**Location**: `hooks/hooks.json` in plugin root, or inline in plugin.json
|
||||
|
||||
**Format**: JSON configuration with event matchers and actions
|
||||
|
||||
**Hook configuration**:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format-code.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Available events**:
|
||||
|
||||
* `PreToolUse`: Before Claude uses any tool
|
||||
* `PostToolUse`: After Claude successfully uses any tool
|
||||
* `PostToolUseFailure`: After Claude tool execution fails
|
||||
* `PermissionRequest`: When a permission dialog is shown
|
||||
* `UserPromptSubmit`: When user submits a prompt
|
||||
* `Notification`: When Claude Code sends notifications
|
||||
* `Stop`: When Claude attempts to stop
|
||||
* `SubagentStart`: When a subagent is started
|
||||
* `SubagentStop`: When a subagent attempts to stop
|
||||
* `SessionStart`: At the beginning of sessions
|
||||
* `SessionEnd`: At the end of sessions
|
||||
* `TeammateIdle`: When an agent team teammate is about to go idle
|
||||
* `TaskCompleted`: When a task is being marked as completed
|
||||
* `PreCompact`: Before conversation history is compacted
|
||||
|
||||
**Hook types**:
|
||||
|
||||
* `command`: Execute shell commands or scripts
|
||||
* `prompt`: Evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context)
|
||||
* `agent`: Run an agentic verifier with tools for complex verification tasks
|
||||
|
||||
### MCP servers
|
||||
|
||||
Plugins can bundle Model Context Protocol (MCP) servers to connect Claude Code with external tools and services.
|
||||
|
||||
**Location**: `.mcp.json` in plugin root, or inline in plugin.json
|
||||
|
||||
**Format**: Standard MCP server configuration
|
||||
|
||||
**MCP server configuration**:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"mcpServers": {
|
||||
"plugin-database": {
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
|
||||
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
|
||||
"env": {
|
||||
"DB_PATH": "${CLAUDE_PLUGIN_ROOT}/data"
|
||||
}
|
||||
},
|
||||
"plugin-api-client": {
|
||||
"command": "npx",
|
||||
"args": ["@company/mcp-server", "--plugin-mode"],
|
||||
"cwd": "${CLAUDE_PLUGIN_ROOT}"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Integration behavior**:
|
||||
|
||||
* Plugin MCP servers start automatically when the plugin is enabled
|
||||
* Servers appear as standard MCP tools in Claude's toolkit
|
||||
* Server capabilities integrate seamlessly with Claude's existing tools
|
||||
* Plugin servers can be configured independently of user MCP servers
|
||||
|
||||
### LSP servers
|
||||
|
||||
<Tip>
|
||||
Looking to use LSP plugins? Install them from the official marketplace: search for "lsp" in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace.
|
||||
</Tip>
|
||||
|
||||
Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase.
|
||||
|
||||
LSP integration provides:
|
||||
|
||||
* **Instant diagnostics**: Claude sees errors and warnings immediately after each edit
|
||||
* **Code navigation**: go to definition, find references, and hover information
|
||||
* **Language awareness**: type information and documentation for code symbols
|
||||
|
||||
**Location**: `.lsp.json` in plugin root, or inline in `plugin.json`
|
||||
|
||||
**Format**: JSON configuration mapping language server names to their configurations
|
||||
|
||||
**`.lsp.json` file format**:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"go": {
|
||||
"command": "gopls",
|
||||
"args": ["serve"],
|
||||
"extensionToLanguage": {
|
||||
".go": "go"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Inline in `plugin.json`**:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"lspServers": {
|
||||
"go": {
|
||||
"command": "gopls",
|
||||
"args": ["serve"],
|
||||
"extensionToLanguage": {
|
||||
".go": "go"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Required fields:**
|
||||
|
||||
| Field | Description |
|
||||
| :-------------------- | :------------------------------------------- |
|
||||
| `command` | The LSP binary to execute (must be in PATH) |
|
||||
| `extensionToLanguage` | Maps file extensions to language identifiers |
|
||||
|
||||
**Optional fields:**
|
||||
|
||||
| Field | Description |
|
||||
| :---------------------- | :-------------------------------------------------------- |
|
||||
| `args` | Command-line arguments for the LSP server |
|
||||
| `transport` | Communication transport: `stdio` (default) or `socket` |
|
||||
| `env` | Environment variables to set when starting the server |
|
||||
| `initializationOptions` | Options passed to the server during initialization |
|
||||
| `settings` | Settings passed via `workspace/didChangeConfiguration` |
|
||||
| `workspaceFolder` | Workspace folder path for the server |
|
||||
| `startupTimeout` | Max time to wait for server startup (milliseconds) |
|
||||
| `shutdownTimeout` | Max time to wait for graceful shutdown (milliseconds) |
|
||||
| `restartOnCrash` | Whether to automatically restart the server if it crashes |
|
||||
| `maxRestarts` | Maximum number of restart attempts before giving up |
|
||||
|
||||
<Warning>
|
||||
**You must install the language server binary separately.** LSP plugins configure how Claude Code connects to a language server, but they don't include the server itself. If you see `Executable not found in $PATH` in the `/plugin` Errors tab, install the required binary for your language.
|
||||
</Warning>
|
||||
|
||||
**Available LSP plugins:**
|
||||
|
||||
| Plugin | Language server | Install command |
|
||||
| :--------------- | :------------------------- | :----------------------------------------------------------------------------------------- |
|
||||
| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |
|
||||
| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |
|
||||
| `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |
|
||||
|
||||
Install the language server first, then install the plugin from the marketplace.
|
||||
|
||||
***
|
||||
|
||||
## Plugin installation scopes
|
||||
|
||||
When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:
|
||||
|
||||
| Scope | Settings file | Use case |
|
||||
| :-------- | :---------------------------- | :------------------------------------------------------- |
|
||||
| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |
|
||||
| `project` | `.claude/settings.json` | Team plugins shared via version control |
|
||||
| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |
|
||||
| `managed` | `managed-settings.json` | Managed plugins (read-only, update only) |
|
||||
|
||||
Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/en/settings#configuration-scopes).
|
||||
|
||||
***
|
||||
|
||||
## Plugin manifest schema
|
||||
|
||||
The `.claude-plugin/plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.
|
||||
|
||||
The manifest is optional. If omitted, Claude Code auto-discovers components in [default locations](#file-locations-reference) and derives the plugin name from the directory name. Use a manifest when you need to provide metadata or custom component paths.
|
||||
|
||||
### Complete schema
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"name": "plugin-name",
|
||||
"version": "1.2.0",
|
||||
"description": "Brief plugin description",
|
||||
"author": {
|
||||
"name": "Author Name",
|
||||
"email": "author@example.com",
|
||||
"url": "https://github.com/author"
|
||||
},
|
||||
"homepage": "https://docs.example.com/plugin",
|
||||
"repository": "https://github.com/author/plugin",
|
||||
"license": "MIT",
|
||||
"keywords": ["keyword1", "keyword2"],
|
||||
"commands": ["./custom/commands/special.md"],
|
||||
"agents": "./custom/agents/",
|
||||
"skills": "./custom/skills/",
|
||||
"hooks": "./config/hooks.json",
|
||||
"mcpServers": "./mcp-config.json",
|
||||
"outputStyles": "./styles/",
|
||||
"lspServers": "./.lsp.json"
|
||||
}
|
||||
```
|
||||
|
||||
### Required fields
|
||||
|
||||
If you include a manifest, `name` is the only required field.
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
| :----- | :----- | :---------------------------------------- | :------------------- |
|
||||
| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |
|
||||
|
||||
This name is used for namespacing components. For example, in the UI, the
|
||||
agent `agent-creator` for the plugin with name `plugin-dev` will appear as
|
||||
`plugin-dev:agent-creator`.
|
||||
|
||||
### Metadata fields
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
| :------------ | :----- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |
|
||||
| `version` | string | Semantic version. If also set in the marketplace entry, `plugin.json` takes priority. You only need to set it in one place. | `"2.1.0"` |
|
||||
| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |
|
||||
| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |
|
||||
| `homepage` | string | Documentation URL | `"https://docs.example.com"` |
|
||||
| `repository` | string | Source code URL | `"https://github.com/user/plugin"` |
|
||||
| `license` | string | License identifier | `"MIT"`, `"Apache-2.0"` |
|
||||
| `keywords` | array | Discovery tags | `["deployment", "ci-cd"]` |
|
||||
|
||||
### Component path fields
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
| :------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- |
|
||||
| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |
|
||||
| `agents` | string\|array | Additional agent files | `"./custom/agents/reviewer.md"` |
|
||||
| `skills` | string\|array | Additional skill directories | `"./custom/skills/"` |
|
||||
| `hooks` | string\|array\|object | Hook config paths or inline config | `"./my-extra-hooks.json"` |
|
||||
| `mcpServers` | string\|array\|object | MCP config paths or inline config | `"./my-extra-mcp-config.json"` |
|
||||
| `outputStyles` | string\|array | Additional output style files/directories | `"./styles/"` |
|
||||
| `lspServers` | string\|array\|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) configs for code intelligence (go to definition, find references, etc.) | `"./.lsp.json"` |
|
||||
|
||||
### Path behavior rules
|
||||
|
||||
**Important**: Custom paths supplement default directories - they don't replace them.
|
||||
|
||||
* If `commands/` exists, it's loaded in addition to custom command paths
|
||||
* All paths must be relative to plugin root and start with `./`
|
||||
* Commands from custom paths use the same naming and namespacing rules
|
||||
* Multiple paths can be specified as arrays for flexibility
|
||||
|
||||
**Path examples**:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"commands": [
|
||||
"./specialized/deploy.md",
|
||||
"./utilities/batch-process.md"
|
||||
],
|
||||
"agents": [
|
||||
"./custom-agents/reviewer.md",
|
||||
"./custom-agents/tester.md"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
**`${CLAUDE_PLUGIN_ROOT}`**: Contains the absolute path to your plugin directory. Use this in hooks, MCP servers, and scripts to ensure correct paths regardless of installation location.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/process.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Plugin caching and file resolution
|
||||
|
||||
Plugins are specified in one of two ways:
|
||||
|
||||
* Through `claude --plugin-dir`, for the duration of a session.
|
||||
* Through a marketplace, installed for future sessions.
|
||||
|
||||
For security and verification purposes, Claude Code copies *marketplace* plugins to the user's local **plugin cache** (`~/.claude/plugins/cache`) rather than using them in-place. Understanding this behavior is important when developing plugins that reference external files.
|
||||
|
||||
### Path traversal limitations
|
||||
|
||||
Installed plugins cannot reference files outside their directory. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache.
|
||||
|
||||
### Working with external dependencies
|
||||
|
||||
If your plugin needs to access files outside its directory, you can create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process:
|
||||
|
||||
```bash theme={null}
|
||||
# Inside your plugin directory
|
||||
ln -s /path/to/shared-utils ./shared-utils
|
||||
```
|
||||
|
||||
The symlinked content will be copied into the plugin cache. This provides flexibility while maintaining the security benefits of the caching system.
|
||||
|
||||
***
|
||||
|
||||
## Plugin directory structure
|
||||
|
||||
### Standard plugin layout
|
||||
|
||||
A complete plugin follows this structure:
|
||||
|
||||
```
|
||||
enterprise-plugin/
|
||||
├── .claude-plugin/ # Metadata directory (optional)
|
||||
│ └── plugin.json # plugin manifest
|
||||
├── commands/ # Default command location
|
||||
│ ├── status.md
|
||||
│ └── logs.md
|
||||
├── agents/ # Default agent location
|
||||
│ ├── security-reviewer.md
|
||||
│ ├── performance-tester.md
|
||||
│ └── compliance-checker.md
|
||||
├── skills/ # Agent Skills
|
||||
│ ├── code-reviewer/
|
||||
│ │ └── SKILL.md
|
||||
│ └── pdf-processor/
|
||||
│ ├── SKILL.md
|
||||
│ └── scripts/
|
||||
├── hooks/ # Hook configurations
|
||||
│ ├── hooks.json # Main hook config
|
||||
│ └── security-hooks.json # Additional hooks
|
||||
├── settings.json # Default settings for the plugin
|
||||
├── .mcp.json # MCP server definitions
|
||||
├── .lsp.json # LSP server configurations
|
||||
├── scripts/ # Hook and utility scripts
|
||||
│ ├── security-scan.sh
|
||||
│ ├── format-code.py
|
||||
│ └── deploy.js
|
||||
├── LICENSE # License file
|
||||
└── CHANGELOG.md # Version history
|
||||
```
|
||||
|
||||
<Warning>
|
||||
The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.
|
||||
</Warning>
|
||||
|
||||
### File locations reference
|
||||
|
||||
| Component | Default Location | Purpose |
|
||||
| :-------------- | :--------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Manifest** | `.claude-plugin/plugin.json` | Plugin metadata and configuration (optional) |
|
||||
| **Commands** | `commands/` | Skill Markdown files (legacy; use `skills/` for new skills) |
|
||||
| **Agents** | `agents/` | Subagent Markdown files |
|
||||
| **Skills** | `skills/` | Skills with `<name>/SKILL.md` structure |
|
||||
| **Hooks** | `hooks/hooks.json` | Hook configuration |
|
||||
| **MCP servers** | `.mcp.json` | MCP server definitions |
|
||||
| **LSP servers** | `.lsp.json` | Language server configurations |
|
||||
| **Settings** | `settings.json` | Default configuration applied when the plugin is enabled. Only [`agent`](/en/sub-agents) settings are currently supported |
|
||||
|
||||
***
|
||||
|
||||
## CLI commands reference
|
||||
|
||||
Claude Code provides CLI commands for non-interactive plugin management, useful for scripting and automation.
|
||||
|
||||
### plugin install
|
||||
|
||||
Install a plugin from available marketplaces.
|
||||
|
||||
```bash theme={null}
|
||||
claude plugin install <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
* `<plugin>`: Plugin name or `plugin-name@marketplace-name` for a specific marketplace
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| :-------------------- | :------------------------------------------------ | :------ |
|
||||
| `-s, --scope <scope>` | Installation scope: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
Scope determines which settings file the installed plugin is added to. For example, --scope project writes to `enabledPlugins` in .claude/settings.json, making the plugin available to everyone who clones the project repository.
|
||||
|
||||
**Examples:**
|
||||
|
||||
```bash theme={null}
|
||||
# Install to user scope (default)
|
||||
claude plugin install formatter@my-marketplace
|
||||
|
||||
# Install to project scope (shared with team)
|
||||
claude plugin install formatter@my-marketplace --scope project
|
||||
|
||||
# Install to local scope (gitignored)
|
||||
claude plugin install formatter@my-marketplace --scope local
|
||||
```
|
||||
|
||||
### plugin uninstall
|
||||
|
||||
Remove an installed plugin.
|
||||
|
||||
```bash theme={null}
|
||||
claude plugin uninstall <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
* `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| :-------------------- | :-------------------------------------------------- | :------ |
|
||||
| `-s, --scope <scope>` | Uninstall from scope: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
**Aliases:** `remove`, `rm`
|
||||
|
||||
### plugin enable
|
||||
|
||||
Enable a disabled plugin.
|
||||
|
||||
```bash theme={null}
|
||||
claude plugin enable <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
* `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| :-------------------- | :--------------------------------------------- | :------ |
|
||||
| `-s, --scope <scope>` | Scope to enable: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
### plugin disable
|
||||
|
||||
Disable a plugin without uninstalling it.
|
||||
|
||||
```bash theme={null}
|
||||
claude plugin disable <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
* `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| :-------------------- | :---------------------------------------------- | :------ |
|
||||
| `-s, --scope <scope>` | Scope to disable: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
### plugin update
|
||||
|
||||
Update a plugin to the latest version.
|
||||
|
||||
```bash theme={null}
|
||||
claude plugin update <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
* `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| :-------------------- | :-------------------------------------------------------- | :------ |
|
||||
| `-s, --scope <scope>` | Scope to update: `user`, `project`, `local`, or `managed` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
***
|
||||
|
||||
## Debugging and development tools
|
||||
|
||||
### Debugging commands
|
||||
|
||||
Use `claude --debug` (or `/debug` within the TUI) to see plugin loading details:
|
||||
|
||||
This shows:
|
||||
|
||||
* Which plugins are being loaded
|
||||
* Any errors in plugin manifests
|
||||
* Command, agent, and hook registration
|
||||
* MCP server initialization
|
||||
|
||||
### Common issues
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
| :---------------------------------- | :------------------------------ | :-------------------------------------------------------------------------------- |
|
||||
| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax with `claude plugin validate` or `/plugin validate` |
|
||||
| Commands not appearing | Wrong directory structure | Ensure `commands/` at root, not in `.claude-plugin/` |
|
||||
| Hooks not firing | Script not executable | Run `chmod +x script.sh` |
|
||||
| MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths |
|
||||
| Path errors | Absolute paths used | All paths must be relative and start with `./` |
|
||||
| LSP `Executable not found in $PATH` | Language server not installed | Install the binary (e.g., `npm install -g typescript-language-server typescript`) |
|
||||
|
||||
### Example error messages
|
||||
|
||||
**Manifest validation errors**:
|
||||
|
||||
* `Invalid JSON syntax: Unexpected token } in JSON at position 142`: check for missing commas, extra commas, or unquoted strings
|
||||
* `Plugin has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: name: Required`: a required field is missing
|
||||
* `Plugin has a corrupt manifest file at .claude-plugin/plugin.json. JSON parse error: ...`: JSON syntax error
|
||||
|
||||
**Plugin loading errors**:
|
||||
|
||||
* `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`: command path exists but contains no valid command files
|
||||
* `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`: the `source` path in marketplace.json points to a non-existent directory
|
||||
* `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`: remove duplicate component definitions or remove `strict: false` in marketplace entry
|
||||
|
||||
### Hook troubleshooting
|
||||
|
||||
**Hook script not executing**:
|
||||
|
||||
1. Check the script is executable: `chmod +x ./scripts/your-script.sh`
|
||||
2. Verify the shebang line: First line should be `#!/bin/bash` or `#!/usr/bin/env bash`
|
||||
3. Check the path uses `${CLAUDE_PLUGIN_ROOT}`: `"command": "${CLAUDE_PLUGIN_ROOT}/scripts/your-script.sh"`
|
||||
4. Test the script manually: `./scripts/your-script.sh`
|
||||
|
||||
**Hook not triggering on expected events**:
|
||||
|
||||
1. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse`
|
||||
2. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations
|
||||
3. Confirm the hook type is valid: `command`, `prompt`, or `agent`
|
||||
|
||||
### MCP server troubleshooting
|
||||
|
||||
**Server not starting**:
|
||||
|
||||
1. Check the command exists and is executable
|
||||
2. Verify all paths use `${CLAUDE_PLUGIN_ROOT}` variable
|
||||
3. Check the MCP server logs: `claude --debug` shows initialization errors
|
||||
4. Test the server manually outside of Claude Code
|
||||
|
||||
**Server tools not appearing**:
|
||||
|
||||
1. Ensure the server is properly configured in `.mcp.json` or `plugin.json`
|
||||
2. Verify the server implements the MCP protocol correctly
|
||||
3. Check for connection timeouts in debug output
|
||||
|
||||
### Directory structure mistakes
|
||||
|
||||
**Symptoms**: Plugin loads but components (commands, agents, hooks) are missing.
|
||||
|
||||
**Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`.
|
||||
|
||||
```
|
||||
my-plugin/
|
||||
├── .claude-plugin/
|
||||
│ └── plugin.json ← Only manifest here
|
||||
├── commands/ ← At root level
|
||||
├── agents/ ← At root level
|
||||
└── hooks/ ← At root level
|
||||
```
|
||||
|
||||
If your components are inside `.claude-plugin/`, move them to the plugin root.
|
||||
|
||||
**Debug checklist**:
|
||||
|
||||
1. Run `claude --debug` and look for "loading plugin" messages
|
||||
2. Check that each component directory is listed in the debug output
|
||||
3. Verify file permissions allow reading the plugin files
|
||||
|
||||
***
|
||||
|
||||
## Distribution and versioning reference
|
||||
|
||||
### Version management
|
||||
|
||||
Follow semantic versioning for plugin releases:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"version": "2.1.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Version format**: `MAJOR.MINOR.PATCH`
|
||||
|
||||
* **MAJOR**: Breaking changes (incompatible API changes)
|
||||
* **MINOR**: New features (backward-compatible additions)
|
||||
* **PATCH**: Bug fixes (backward-compatible fixes)
|
||||
|
||||
**Best practices**:
|
||||
|
||||
* Start at `1.0.0` for your first stable release
|
||||
* Update the version in `plugin.json` before distributing changes
|
||||
* Document changes in a `CHANGELOG.md` file
|
||||
* Use pre-release versions like `2.0.0-beta.1` for testing
|
||||
|
||||
<Warning>
|
||||
Claude Code uses the version to determine whether to update your plugin. If you change your plugin's code but don't bump the version in `plugin.json`, your plugin's existing users won't see your changes due to caching.
|
||||
|
||||
If your plugin is within a [marketplace](/en/plugin-marketplaces) directory, you can manage the version through `marketplace.json` instead and omit the `version` field from `plugin.json`.
|
||||
</Warning>
|
||||
|
||||
***
|
||||
|
||||
## See also
|
||||
|
||||
* [Plugins](/en/plugins) - Tutorials and practical usage
|
||||
* [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces
|
||||
* [Skills](/en/skills) - Skill development details
|
||||
* [Subagents](/en/sub-agents) - Agent configuration and capabilities
|
||||
* [Hooks](/en/hooks) - Event handling and automation
|
||||
* [MCP](/en/mcp) - External tool integration
|
||||
* [Settings](/en/settings) - Configuration options for plugins
|
||||
Reference in New Issue
Block a user