### Bash Hook Example for PreToolUse Source: https://context7.com/hcd233/clawd-kobe/llms.txt An example Bash script for a PreToolUse hook that reads input from stdin, parses the tool command, and decides whether to block potentially dangerous commands. ```bash #!/bin/bash # hooks/validate-bash.sh - Example PreToolUse hook # Read hook input from stdin INPUT=$(cat) COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command') # Block dangerous commands if echo "$COMMAND" | grep -qE "rm -rf|:(){ :|&};:"; then echo '{"decision": "block", "reason": "Potentially dangerous command blocked"}' exit 0 fi # Allow safe commands echo '{"decision": "approve"}' ``` -------------------------------- ### Skill Definition Frontmatter Source: https://context7.com/hcd233/clawd-kobe/llms.txt Markdown frontmatter example for defining a skill, including its name, description, allowed tools, and model. ```markdown --- name: deploy description: Deploy the application to production tools: [Bash, Read, Write] model: sonnet --- # Deploy Skill When the user invokes /deploy, follow these steps: 1. Run the test suite to ensure all tests pass 2. Build the production bundle 3. Deploy to the configured environment ## Prerequisites - Ensure all environment variables are set - Verify AWS credentials are configured ## Deployment Steps ```bash npm run test npm run build aws s3 sync ./dist s3://my-bucket/ ``` ``` -------------------------------- ### Configure MCP Servers Source: https://context7.com/hcd233/clawd-kobe/llms.txt Configures MCP servers via project-level JSON or programmatically using the SDK. ```json // .mcp.json - Project-level MCP configuration { "mcpServers": { "filesystem": { "type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"] }, "github": { "type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" } }, "remote-api": { "type": "sse", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer ${API_TOKEN}" } } } } ``` ```typescript // Programmatic MCP server configuration via SDK import { createSdkMcpServer, tool } from '@anthropic-ai/claude-code'; import { z } from 'zod'; // Define custom tools const myTool = tool( "my_custom_tool", "Performs a custom operation", { input: z.string() }, async (args) => { return { content: [{ type: "text", text: `Processed: ${args.input}` }] }; } ); // Create SDK MCP server const mcpServer = createSdkMcpServer({ name: "my-sdk-server", version: "1.0.0", tools: [myTool] }); ``` -------------------------------- ### Configure Permission Rules in settings.json Source: https://context7.com/hcd233/clawd-kobe/llms.txt Specify allowed and denied tool usage patterns in settings.json to enforce security and control agent actions. ```json { "permissions": { "allow": [ "Bash(git *)", "Bash(npm test)", "Read(*)", "Glob(*)", "Grep(*)" ], "deny": [ "Bash(rm -rf *)", "Bash(sudo *)", "WebFetch(domain:*.internal.com)" ] } } ``` -------------------------------- ### Permission System Configuration Source: https://context7.com/hcd233/clawd-kobe/llms.txt Manage tool execution permissions using modes and explicit allow/deny rules. ```APIDOC ## Permissions Configuration ### Description Define fine-grained control over tool permissions through modes and explicit rules in settings.json. ### Request Body - **permissions** (object) - Required - Permission rules. - **allow** (array) - Optional - List of allowed tool patterns. - **deny** (array) - Optional - List of denied tool patterns. ### Request Example { "permissions": { "allow": ["Bash(git *)", "Read(*)"], "deny": ["Bash(rm -rf *)"] } } ``` -------------------------------- ### Skill Definition Source: https://context7.com/hcd233/clawd-kobe/llms.txt Define custom slash commands using markdown files with frontmatter. ```APIDOC ## Skill Definition ### Description Skills are defined via markdown files containing frontmatter that specifies the command name, description, and tool constraints. ### Frontmatter Fields - **name** (string) - Required - The slash command name (without /). - **description** (string) - Required - Description of the skill. - **tools** (array) - Optional - List of allowed tools. - **model** (string) - Optional - Model override. ### Example --- name: deploy description: Deploy the application to production tools: [Bash, Read, Write] model: sonnet --- ``` -------------------------------- ### query - Execute Single-Turn Agent Queries Source: https://context7.com/hcd233/clawd-kobe/llms.txt The `query` function is the primary entry point for running single-turn agent queries. It takes a prompt and options, executing the agent loop and streaming results back to the caller. ```APIDOC ## POST /query ### Description Executes a single-turn agent query with a given prompt and options, streaming results back. ### Method POST ### Endpoint /query ### Parameters #### Request Body - **prompt** (string) - Required - The user's prompt for the agent. - **options** (object) - Required - Configuration options for the query. - **model** (string) - Required - The Claude model to use (e.g., 'claude-sonnet-4-6'). - **permissionMode** (string) - Optional - The permission mode for tool execution (e.g., 'default'). - **maxTurns** (number) - Optional - The maximum number of turns for the agent loop. - **cwd** (string) - Optional - The current working directory for the agent. ### Request Example ```json { "prompt": "What files are in the current directory?", "options": { "model": "claude-sonnet-4-6", "permissionMode": "default", "maxTurns": 10, "cwd": "/path/to/project" } } ``` ### Response #### Success Response (200) - **type** (string) - The type of message received (e.g., 'assistant', 'result'). - **message** (object) - Contains the assistant's message content if type is 'assistant'. - **content** (string) - The assistant's response. - **result** (object) - Contains the final result if type is 'result'. - **total_cost_usd** (number) - The total cost of the query in USD. #### Response Example ```json { "type": "assistant", "message": { "content": "The files in the current directory are: ..." } } ``` ```json { "type": "result", "result": { "files": ["file1.txt", "file2.js"] }, "total_cost_usd": 0.0005 } ``` ``` -------------------------------- ### Hooks System Configuration Source: https://context7.com/hcd233/clawd-kobe/llms.txt Configure custom code execution at specific agent lifecycle events such as PreToolUse, PostToolUse, and SessionStart. ```APIDOC ## Hooks Configuration ### Description Hooks allow custom code execution at various points in the agent lifecycle. Configuration is defined in settings.json. ### Request Body - **hooks** (object) - Required - Map of event names to hook configurations. - **PreToolUse** (array) - Optional - List of hooks to run before tool execution. - **PostToolUse** (array) - Optional - List of hooks to run after tool execution. - **SessionStart** (array) - Optional - List of hooks to run at session initialization. ### Request Example { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": ["./hooks/validate-bash.sh"] } ] } } ``` -------------------------------- ### listSessions - List Available Sessions Source: https://context7.com/hcd233/clawd-kobe/llms.txt Lists all sessions with metadata, supporting pagination and project filtering. ```APIDOC ## GET /sessions ### Description Lists available sessions with metadata, supporting pagination and project filtering. ### Method GET ### Endpoint /sessions ### Parameters #### Query Parameters - **dir** (string) - Optional - The directory to filter sessions by. - **limit** (number) - Optional - The maximum number of sessions to return (default: 50). - **offset** (number) - Optional - The number of sessions to skip for pagination (default: 0). ### Response #### Success Response (200) - **sessionId** (string) - The unique identifier for the session. - **summary** (string) - A brief summary of the session. - **lastModified** (string) - The timestamp when the session was last modified. - **gitBranch** (string) - The Git branch associated with the session (if any). #### Response Example ```json [ { "sessionId": "session-uuid-abcde", "summary": "Initial setup for project X", "lastModified": "2023-10-27T10:00:00Z", "gitBranch": "main" }, { "sessionId": "session-uuid-fghij", "summary": "Refactoring component Y", "lastModified": "2023-10-27T11:30:00Z", "gitBranch": "feature/new-ui" } ] ``` ``` -------------------------------- ### Configure Hooks in settings.json Source: https://context7.com/hcd233/clawd-kobe/llms.txt Define hook configurations in settings.json to specify which scripts or functions to run for different hook events like PreToolUse or PostToolUse. ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": ["./hooks/validate-bash.sh"] } ], "PostToolUse": [ { "matcher": "*", "hooks": ["./hooks/log-tool-use.js"] } ], "SessionStart": [ { "hooks": ["./hooks/setup-environment.sh"] } ] } } ``` -------------------------------- ### List Available Sessions with listSessions Source: https://context7.com/hcd233/clawd-kobe/llms.txt The `listSessions` function retrieves metadata for available sessions, supporting pagination and project filtering. Specify the directory, limit, and offset for the query. ```typescript import { listSessions } from '@anthropic-ai/claude-code'; // List sessions for a specific project const sessions = await listSessions({ dir: '/path/to/project', limit: 50, offset: 0 }); for (const session of sessions) { console.log(`Session: ${session.sessionId}`); console.log(` Summary: ${session.summary}`); console.log(` Last Modified: ${new Date(session.lastModified)}`); console.log(` Branch: ${session.gitBranch || 'N/A'}`); } ``` -------------------------------- ### unstable_v2_prompt - One-Shot Convenience Function Source: https://context7.com/hcd233/clawd-kobe/llms.txt A simplified one-shot function for single prompts that don't require session management. ```APIDOC ## POST /prompt ### Description A one-shot convenience function for executing single prompts without explicit session management. ### Method POST ### Endpoint /prompt ### Parameters #### Request Body - **prompt** (string) - Required - The prompt to send to the agent. - **options** (object) - Optional - Configuration options for the prompt. - **model** (string) - Required - The Claude model to use (e.g., 'claude-sonnet-4-6'). - **cwd** (string) - Optional - The current working directory for the prompt. ### Request Example ```json { "prompt": "Explain the purpose of this file: package.json", "options": { "model": "claude-sonnet-4-6", "cwd": "/path/to/project" } } ``` ### Response #### Success Response (200) - **result** (object) - The result of the prompt execution. - **explanation** (string) - The explanation provided by the agent. - **usage** (object) - Information about token usage. - **input_tokens** (number) - The number of input tokens used. - **output_tokens** (number) - The number of output tokens used. #### Response Example ```json { "result": { "explanation": "The package.json file is used to manage dependencies and metadata for Node.js projects." }, "usage": { "input_tokens": 150, "output_tokens": 50 } } ``` ``` -------------------------------- ### Fetch and Process Web Content Source: https://context7.com/hcd233/clawd-kobe/llms.txt Fetches URL content and converts it to markdown for processing. ```typescript // Fetch and summarize a webpage const fetchInput = { url: "https://docs.example.com/api/reference", prompt: "Extract all the API endpoints and their descriptions" }; // Result { "bytes": 45000, "code": 200, "codeText": "OK", "result": "Found 15 API endpoints:\n1. GET /users - List all users\n2. POST /users - Create user...", "durationMs": 2500, "url": "https://docs.example.com/api/reference" } ``` -------------------------------- ### Perform One-Shot Queries with unstable_v2_prompt Source: https://context7.com/hcd233/clawd-kobe/llms.txt Use `unstable_v2_prompt` for simple, single-prompt queries that do not require session management. It returns the result and token usage information. ```typescript import { unstable_v2_prompt } from '@anthropic-ai/claude-code'; // Simple one-shot query const result = await unstable_v2_prompt( "Explain the purpose of this file: package.json", { model: 'claude-sonnet-4-6', cwd: '/path/to/project' } ); console.log('Response:', result.result); console.log('Tokens used:', result.usage); ``` -------------------------------- ### Launch Subagents with Task Tool Source: https://context7.com/hcd233/clawd-kobe/llms.txt Configures and launches specialized subagents for autonomous tasks, supporting background execution and resuming previous sessions. ```typescript // Launch a general-purpose research agent const taskInput = { description: "Find authentication code", prompt: "Search the codebase and explain how user authentication is implemented. Look at login flows, session management, and any OAuth integrations.", subagent_type: "general-purpose", model: "haiku" // Optional: use faster model for simple tasks }; // Launch agent in background const backgroundAgent = { description: "Run full test suite", prompt: "Run all tests and fix any failures you find", subagent_type: "general-purpose", run_in_background: true }; // Resume a previous agent const resumeAgent = { description: "Continue previous work", prompt: "Continue investigating the bug", resume: "agent-id-from-previous-run" }; // Result (sync completion) { "status": "completed", "result": "Found authentication implementation in src/auth/...", "usage": { "inputTokens": 5000, "outputTokens": 2000 } } // Result (async/background) { "status": "async_launched", "agentId": "agent-abc123", "outputFile": "/path/to/agent-output.jsonl" } ``` -------------------------------- ### Create Persistent Multi-Turn Sessions with unstable_v2_createSession Source: https://context7.com/hcd233/clawd-kobe/llms.txt Utilize `unstable_v2_createSession` to establish persistent sessions for multi-turn conversations, maintaining state across interactions. Configure model, working directory, permission mode, and system prompt. ```typescript import { unstable_v2_createSession } from '@anthropic-ai/claude-code'; // Create a new persistent session const session = unstable_v2_createSession({ model: 'claude-sonnet-4-6', cwd: '/path/to/project', permissionMode: 'acceptEdits', systemPrompt: 'You are a helpful coding assistant.' }); // Send messages within the session const response1 = await session.send("Create a new React component"); console.log(response1); const response2 = await session.send("Now add TypeScript types to it"); console.log(response2); // Session maintains context across turns await session.close(); ``` -------------------------------- ### Define a custom agent configuration Source: https://context7.com/hcd233/clawd-kobe/llms.txt Use this JSON structure to define subagent capabilities, tools, and memory settings. ```json // .claude/agents/code-reviewer.json { "description": "Reviews code changes for quality and best practices", "prompt": "You are a code reviewer. Analyze the provided code changes for:\n- Code quality\n- Potential bugs\n- Performance issues\n- Security concerns\n\nProvide specific, actionable feedback.", "tools": ["Read", "Glob", "Grep", "LSP"], "model": "sonnet", "maxTurns": 20, "memory": "project" } ``` -------------------------------- ### Find Files by Pattern Source: https://context7.com/hcd233/clawd-kobe/llms.txt Fast file pattern matching using glob patterns, returning files sorted by modification time. Results are limited to 100 files. ```typescript // Find all TypeScript files const globInput = { pattern: "**/*.ts", path: "/path/to/project" // Optional, defaults to cwd }; // Find specific file types in subdirectory const specificGlob = { pattern: "src/components/**/*.tsx" }; // Result { "durationMs": 45, "numFiles": 23, "filenames": [ "src/components/App.tsx", "src/components/Header.tsx", "src/components/Footer.tsx" ], "truncated": false // Limited to 100 files } ``` -------------------------------- ### Create or Overwrite Files Source: https://context7.com/hcd233/clawd-kobe/llms.txt Writes content to files, creating new files or completely overwriting existing ones. The result indicates the type of operation ('create' or 'update'). ```typescript // Create new file const writeInput = { file_path: "/path/to/new-file.ts", content: `import React from 'react'; export function MyComponent() { return