New advertisers: 50% off your first month with code FIRSTMONTHSee slots

Claude Code SDK integration for AI-powered applications

version
1.0.0
GitHub stars
26
View on GitHub

Add marketplace

/plugin marketplace add miles990/claude-software-skills

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install claude-code-sdk@claude-software-skills

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

Claude Code SDK Integration

Overview

Claude Code SDK (claude-code-sdk) 是 Anthropic 官方提供的 Python 套件,用於在應用程式中整合 Claude AI Agent 功能。它支援 OAuth 認證(透過 claude login)和 API Key 認證,讓開發者可以利用 Claude Max/Pro 訂閱或 API 計費方案。這個 SDK 是建立 AI-powered 應用程式的關鍵工具,特別適合需要程式碼生成、檔案操作、或多輪對話的場景。

Key Concepts

認證方式

Description: Claude Code SDK 支援兩種認證方式 Key Features:

  • OAuth 認證: 使用 claude login 後存儲在 ~/.claude/ 的憑證
  • API Key 認證: 透過 ANTHROPIC_API_KEY 環境變數

Use Cases:

  • OAuth:個人開發、有 Max/Pro 訂閱的用戶
  • API Key:生產環境、需要計量計費的服務

SDK 核心 API

Description: query() 函數是主要的非同步介面 Key Features:

  • 非同步迭代器回傳訊息
  • 支援 streaming 和完整回應
  • 可配置工具權限和執行限制

Use Cases: 程式碼生成、檔案操作、研究任務、唯讀分析

工具類型 (ToolType)

Description: SDK 支援多種內建工具 Key Features:

  • READ, WRITE, EDIT - 檔案操作
  • BASH - 終端命令執行
  • GLOB, GREP - 檔案搜尋
  • WEB_FETCH - 網頁抓取

Best Practices

  1. 雙重認證檢查
    • 同時支援 OAuth 和 API Key
    • 優先使用 OAuth(免費使用 Max/Pro 配額)
    • API Key 作為後備方案
def check_auth_status() -> dict:
    status = {
        'api_key_set': bool(os.environ.get('ANTHROPIC_API_KEY')),
        'oauth_logged_in': False,
    }

    # 檢查 OAuth 登入狀態
    claude_dir = os.path.expanduser('~/.claude')
    if os.path.exists(claude_dir):
        auth_files = ['credentials.json', 'settings.json', '.credentials.json']
        for auth_file in auth_files:
            if os.path.exists(os.path.join(claude_dir, auth_file)):
                status['oauth_logged_in'] = True
                break

    # 只需要其中一種認證
    status['auth_available'] = status['api_key_set'] or status['oauth_logged_in']
    return status
  1. 增加 Buffer Size
    • 預設 buffer 太小,處理大型回應會出錯
    • 建議增加到 50MB
try:
    from claude_code_sdk._internal.transport import subprocess_cli
    subprocess_cli._MAX_BUFFER_SIZE = 50 * 1024 * 1024  # 50MB
except Exception as e:
    print(f"Failed to patch SDK buffer size: {e}")
  1. 使用 Singleton Pattern
    • 避免重複初始化
    • 共享狀態和配置
_claude_service: Optional['ClaudeCodeService'] = None

def get_claude_code() -> 'ClaudeCodeService':
    global _claude_service
    if _claude_service is None:
        _claude_service = ClaudeCodeService()
    return _claude_service
  1. 預設配置模式
    • 依據使用場景限制工具權限
    • 降低風險,提升安全性
@dataclass
class AgentConfig:
    allowed_tools: List[str]
    max_turns: int = 30
    cwd: Optional[str] = None

    @classmethod
    def coding(cls) -> 'AgentConfig':
        """開發模式:完整權限"""
        return cls(
            allowed_tools=['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'],
            max_turns=50
        )

    @classmethod
    def research(cls) -> 'AgentConfig':
        """研究模式:可上網"""
        return cls(
            allowed_tools=['Read', 'Glob', 'Grep', 'WebFetch'],
            max_turns=20
        )

    @classmethod
    def readonly(cls) -> 'AgentConfig':
        """唯讀模式:最安全"""
        return cls(
            allowed_tools=['Read', 'Glob', 'Grep'],
            max_turns=10
        )

Common Pitfalls

Pitfall 1: 直接在前端呼叫 SDK

  • Problem: claude-code-sdk 是 Python 套件,無法在瀏覽器中運行
  • Solution: 必須建立後端 API 服務
  • Example:
# ❌ 錯誤:嘗試在前端使用
# JavaScript 無法直接使用 Python SDK

# ✅ 正確:建立 FastAPI 後端
from fastapi import FastAPI
from claude_code_sdk import query

app = FastAPI()

@app.post("/api/generate")
async def generate(prompt: str):
    result = []
    async for msg in query(prompt=prompt):
        result.append(msg)
    return {"result": result}

Pitfall 2: 忘記處理非同步

  • Problem: SDK 是非同步的,忘記 await 會導致錯誤
  • Solution: 使用 async/await 或 asyncio
# ❌ 錯誤
def run_sync():
    for msg in query(prompt="Hello"):  # TypeError
        print(msg)

# ✅ 正確
async def run_async():
    async for msg in query(prompt="Hello"):
        print(msg)

Pitfall 3: 混淆 Claude API 和 Claude Code SDK

  • Problem:
    • Claude API (anthropic 套件) - 直接 HTTP API,需要 API Key
    • Claude Code SDK (claude-code-sdk) - Agent 功能,支援 OAuth
  • Solution: 根據需求選擇正確的套件
特性Claude APIClaude Code SDK
認證API Key onlyOAuth + API Key
功能純對話Agent (檔案/終端操作)
計費API 用量計費Max/Pro 訂閱可用
套件anthropicclaude-code-sdk

Patterns & Anti-Patterns

Patterns (Do This)

完整的服務封裝:

from dataclasses import dataclass, field
from typing import AsyncIterator, Optional, List, Dict, Any
from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock

@dataclass
class ClaudeCodeService:
    """Claude Code 服務封裝"""

    async def run(self, prompt: str, config: Optional[AgentConfig] = None) -> Dict[str, Any]:
        """執行並收集完整結果"""
        options = ClaudeCodeOptions(
            allowed_tools=config.allowed_tools if config else None,
            max_turns=config.max_turns if config else 30,
            cwd=config.cwd
        )

        result_texts = []
        tool_calls = []

        async for message in query(prompt=prompt, options=options):
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        result_texts.append(block.text)

        return {
            'status': 'success',
            'result': '\n'.join(result_texts),
            'tool_calls': tool_calls
        }

    async def stream(self, prompt: str, config: Optional[AgentConfig] = None) -> AsyncIterator[dict]:
        """串流執行,即時回傳"""
        options = ClaudeCodeOptions(
            allowed_tools=config.allowed_tools if config else None,
            max_turns=config.max_turns if config else 30
        )

        async for message in query(prompt=prompt, options=options):
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        yield {'type': 'text', 'content': block.text}

FastAPI 串流端點:

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import json

app = FastAPI()

@app.post("/api/agent/stream")
async def agent_stream(prompt: str):
    async def event_generator():
        service = ClaudeCodeService()
        async for msg in service.stream(prompt):
            yield f"data: {json.dumps(msg)}\n\n"
        yield "data: [DONE]\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream"
    )

Anti-Patterns (Avoid This)

# ❌ 不要在每次請求都建立新服務
@app.post("/api/generate")
async def bad_generate(prompt: str):
    service = ClaudeCodeService()  # 每次都新建
    return await service.run(prompt)

# ❌ 不要忽略錯誤處理
async def bad_run(prompt: str):
    async for msg in query(prompt=prompt):  # 可能拋出異常
        print(msg)

# ❌ 不要給予過多權限
config = AgentConfig(
    allowed_tools=['Read', 'Write', 'Edit', 'Bash', 'WebFetch'],  # 全開
    max_turns=100  # 太多
)

Tools & Resources

ToolPurposeLink
claude-code-sdk官方 Python SDKpip install claude-code-sdk
Claude Code CLI命令列工具npm install -g @anthropic-ai/claude-code
FastAPI後端框架fastapi.tiangolo.com

Decision Guide

Use Claude Code SDK when:

  • 需要 Agent 功能(檔案操作、終端命令)
  • 想使用 Max/Pro 訂閱而非 API 計費
  • 建立需要多輪互動的 AI 應用
  • 需要串流即時回應

Consider alternatives when:

  • 只需要簡單對話 → 使用 anthropic 套件
  • 純前端應用 → 使用 anthropic + anthropic-dangerous-direct-browser-access
  • 不需要 Agent 功能 → 使用標準 Claude API

Examples

Example 1: 完整後端服務

Context: 建立一個可以利用 Claude Max 訂閱的後端 API

Implementation:

# backend/main.py
import os
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import json

from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock

app = FastAPI()

# CORS 設定
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

class GenerateRequest(BaseModel):
    prompt: str
    max_turns: int = 30

def check_auth():
    """檢查認證狀態"""
    api_key = bool(os.environ.get('ANTHROPIC_API_KEY'))
    oauth = os.path.exists(os.path.expanduser('~/.claude/credentials.json'))
    return api_key or oauth

@app.get("/api/health")
async def health():
    return {
        "status": "ok",
        "auth_available": check_auth()
    }

@app.post("/api/generate")
async def generate(request: GenerateRequest):
    if not check_auth():
        raise HTTPException(401, "請先執行 claude login 或設置 ANTHROPIC_API_KEY")

    options = ClaudeCodeOptions(max_turns=request.max_turns)
    results = []

    async for message in query(prompt=request.prompt, options=options):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    results.append(block.text)

    return {"result": "\n".join(results)}

@app.post("/api/stream")
async def stream(request: GenerateRequest):
    if not check_auth():
        raise HTTPException(401, "未認證")

    async def event_generator():
        options = ClaudeCodeOptions(max_turns=request.max_turns)
        async for message in query(prompt=request.prompt, options=options):
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        yield f"data: {json.dumps({'text': block.text})}\n\n"
        yield "data: [DONE]\n\n"

    return StreamingResponse(event_generator(), media_type="text/event-stream")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

requirements.txt:

fastapi>=0.100.0
uvicorn>=0.23.0
claude-code-sdk>=0.1.0
python-dotenv>=1.0.0

Explanation: 這個後端會自動檢測 OAuth 或 API Key 認證,支援一般請求和串流回應。

Example 2: 前端整合

Context: 前端呼叫後端 API

Implementation:

// 一般請求
async function generate(prompt) {
    const response = await fetch('http://localhost:8000/api/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt })
    });
    const data = await response.json();
    return data.result;
}

// 串流請求
async function streamGenerate(prompt, onChunk) {
    const response = await fetch('http://localhost:8000/api/stream', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt })
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
            if (line.startsWith('data: ') && line !== 'data: [DONE]') {
                const data = JSON.parse(line.slice(6));
                onChunk(data.text);
            }
        }
    }
}

Example 3: Docker 部署

Context: 容器化部署包含 Claude Code CLI

Implementation:

# Dockerfile
FROM python:3.11-slim

# 安裝 Node.js (Claude Code CLI 需要)
RUN apt-get update && apt-get install -y curl && \
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
    apt-get install -y nodejs && \
    rm -rf /var/lib/apt/lists/*

# 安裝 Claude Code CLI
RUN npm install -g @anthropic-ai/claude-code

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# docker-compose.yml
version: '3.8'
services:
  backend:
    build: .
    ports:
      - "8000:8000"
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
    volumes:
      - ~/.claude:/root/.claude:ro  # 掛載 OAuth 憑證

Related Skills

  • [[api-design]] - 設計 REST API 端點
  • [[backend]] - Python/FastAPI 後端開發
  • [[devops-cicd]] - Docker 部署和 CI/CD
  • [[security-practices]] - API 認證和安全

References

From the miles990/claude-software-skills README

Claude Software Skills

55 modular software development skills for Claude Code - from architecture to deployment

Skills Categories Plugin

┌─────────────────────────────────────────────────────────────────┐
│                  Claude Software Skills                         │
│                                                                 │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│   │   Software   │  │   Software   │  │ Development  │         │
│   │    Design    │  │ Engineering  │  │    Stacks    │         │
│   │      6       │  │      8       │  │      8       │         │
│   └──────────────┘  └──────────────┘  └──────────────┘         │
│                                                                 │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│   │    Tools &   │  │   Domain     │  │ Programming  │         │
│   │ Integrations │  │ Applications │  │  Languages   │         │
│   │      9       │  │     12       │  │     12       │         │
│   └──────────────┘  └──────────────┘  └──────────────┘         │
│                                                                 │
│              AI 自動識別任務 → 載入對應領域知識                 │
└─────────────────────────────────────────────────────────────────┘

Features

  • MCP Compatible - Works with Claude Code, Cursor, and other MCP clients
  • Semantic Search - Claude automatically finds relevant skills for your task
  • Cross-Domain Integration - Skills work together seamlessly
  • Best Practices Built-In - Each skill includes patterns and anti-patterns
  • Modular Architecture - Use only what you need
  • Sharp Edges - Proactive warnings about common pitfalls with detection patterns
  • Validations - Executable code quality rules with regex/ast patterns
  • Collaboration - Skills declare relationships for smart delegation and context passing

Installation

Plugin Marketplace (Recommended)

# 1. Add marketplace (GitHub format: owner/repo)
/plugin marketplace add miles990/claude-software-skills

# 2. Open plugin management interface, view available plugins in Discover tab
/plugin

# 3. Install specific skills (choose what you need)
/plugin install frontend@claude-software-skills
/plugin install backend@claude-software-skills
/plugin install api-design@claude-software-skills

# Or mention skill name in conversation, Claude will auto-load

Supported GitHub formats:

# Short format (recommended)
/plugin marketplace add miles990/claude-software-skills

# HTTPS URL
/plugin marketplace add https://github.com/miles990/claude-software-skills.git

# Specify branch or tag
/plugin marketplace add miles990/claude-software-skills#main

Plugin commands:

CommandDescription
/pluginOpen interactive plugin management interface
/plugin install <name>@<marketplace>Install specific plugin
/plugin disable <name>@<marketplace>Temporarily disable plugin
/plugin uninstall <name>@<marketplace>Completely remove plugin

Available Skills

Software Design (6 skills)

SkillDescription
architecture-patternsSoftware architecture patterns and best practices
design-patternsClassic and modern software design patterns
api-designRESTful, GraphQL, gRPC, and API best practices
system-designScalability, availability, and distributed systems design
data-designData modeling, schema design, and data architecture
ux-principlesUser experience design principles for developers

Software Engineering (8 skills)

SkillDescription
code-qualityClean code principles, SOLID, and code review practices
testing-strategiesUnit, integration, E2E testing and TDD practices
devops-cicdCI/CD pipelines, infrastructure as code, and deployment
performance-optimizationProfiling, optimization techniques, and best practices
security-practicesOWASP Top 10, authentication, and secure coding
reliability-engineeringSRE principles, observability, and incident management
documentationTechnical writing, API docs, and documentation best practices
internationalizationi18n/l10n architecture design and multi-language support

Development Stacks (8 skills)

SkillDescription
frontendModern frontend with React, Vue, and web technologies
backendBackend with Node.js, Express, NestJS, and server patterns
mobileMobile with React Native, Flutter, and native patterns
databaseDatabase design, SQL, NoSQL, and data management
cloud-platformsAWS, GCP, Azure services and cloud-native development
ai-ml-integrationAI/ML APIs, LLM integration, and intelligent apps
realtime-systemsWebSocket, real-time communication, event-driven
edge-iotEdge computing, IoT protocols, and embedded systems

Tools & Integrations (9 skills)

SkillDescription
git-workflowsGit version control, branching, and collaboration
project-managementAgile, Scrum, Kanban, and issue tracking
development-environmentIDE setup, dev containers, and local development
monitoring-loggingApplication monitoring, logging, and alerting
api-toolsAPI testing, documentation, and development tools
automation-scriptsBuild automation, task runners, and scripting
auto-dev-setupAuto-Dev workflow for Human-in-the-Loop automation
claude-code-pluginClaude Code Plugin development and marketplace management
claude-code-sdkClaude Code SDK for AI-powered applications

Domain Applications (12 skills)

SkillDescription
application-patternsCommon application development patterns
e-commerceE-commerce platforms, payments, shopping cart
saas-platformsSaaS architecture, multi-tenancy, subscriptions
content-platformsCMS, blogging platforms, content management
communication-systemsEmail, notifications, messaging systems
developer-toolsCLI tools, SDKs, developer experience
game-developmentGame development patterns and architectures
flameFlame Engine 2D game development for Flutter
flame-coreFlame Engine core - components, input, collision
flame-systemsFlame Engine 14 game systems
flame-templatesGame templates - RPG, Platformer, Roguelike
desktop-appsDesktop apps with Electron and Tauri

Programming Languages (12 skills)

SkillDescription
javascript-typescriptModern JavaScript and TypeScript patterns
pythonPython programming patterns and best practices
goGo programming patterns and idioms
rustRust patterns and ownership concepts
java-kotlinJava and Kotlin programming patterns
csharp-dotnetC# and .NET development patterns
cppModern C++ programming patterns and idioms
rubyRuby programming patterns and idioms
phpModern PHP programming patterns
swiftSwift patterns for iOS and macOS
shell-bashShell scripting and Bash programming
sqlSQL patterns for database querying and design

Other Installation Methods

Clone to Skills Directory

# Clone to your skills directory
git clone https://github.com/miles990/claude-software-skills.git ~/.claude/skills/software-skills

Claude will automatically discover and use the skills when relevant to your tasks.

With MCP Server

This repository is compatible with claude-skills-mcp:

# Install the MCP server
pip install claude-skills-mcp

# Add this repository as a skill source
# The server will load skills from ~/.claude/skills/

Cursor IDE

Add to your Cursor MCP settings:

{
  "mcpServers": {
    "software-skills": {
      "command": "npx",
      "args": ["-y", "claude-skills-mcp"],
      "env": {
        "SKILLS_PATH": "/path/to/claude-software-skills"
      }
    }
  }
}

Manual Reference

Simply clone and reference the SKILL.md files in your prompts:

git clone https://github.com/miles990/claude-software-skills.git

Auto-Dev: Automated Development Workflow

One-click setup for GitHub Actions automated development workflow, let Claude help you complete development tasks.

Quick Setup

Using API Key:

curl -fsSL https://raw.githubusercontent.com/miles990/claude-software-skills/main/scripts/setup-auto-dev-apikey.sh | bash

Using Claude Max (OAuth):

curl -fsSL https://raw.githubusercontent.com/miles990/claude-software-skills/main/scripts/setup-auto-dev-max.sh | bash

Post-Installation Setup

VersionSetup Method
API KeyGet Key from console.anthropic.com, set in GitHub Secrets ANTHROPIC_API_KEY
Claude MaxRun claude /install-github-app for auto OAuth Token setup

Usage

  • Issue Trigger: Create Issue → Add auto-dev label
  • Comment Trigger: Comment @claude [instruction] on any Issue/PR

Detailed docs: AUTO-DEV.md

Usage Examples

User: Help me design a microservices architecture for an e-commerce platform

Claude: [Automatically uses architecture-patterns + e-commerce + api-design skills]
User: Review this Python code for performance issues

Claude: [Automatically uses python + performance-optimization + code-quality skills]
User: Set up CI/CD for a React + Node.js monorepo

Claude: [Automatically uses devops-cicd + frontend + backend + git-workflows skills]

Directory Structure

claude-software-skills/
├── .claude-plugin/          # Plugin configuration
│   └── marketplace.json     # Lists all 55 skills as individual plugins
├── .github/
│   └── workflows/           # CI/CD automation
├── software-design/         # Architecture & design skills
├── software-engineering/    # Development practices
├── development-stacks/      # Tech stack skills
├── tools-integrations/      # Developer tools
├── domain-applications/     # Domain-specific patterns
├── programming-languages/   # Language-specific skills
├── docs/
│   ├── SKILL-TEMPLATE.md    # Template for new skills
│   └── software-skills.md
├── CONTRIBUTING.md
├── LICENSE
└── README.md

How It Works

Each skill module contains a SKILL.md file with:

  1. Metadata - Name, description, tags for semantic search
  2. Key Concepts - Core knowledge and terminology
  3. Best Practices - Recommended approaches with examples
  4. Common Pitfalls - What to avoid and why
  5. Patterns & Anti-patterns - Do's and don'ts with code
  6. Tools & Resources - Recommended tools and references
  7. Decision Guide - When to use this skill

When you describe a task, Claude:

  1. Searches for relevant skills using semantic matching
  2. Loads the appropriate SKILL.md files
  3. Applies the knowledge to your specific context
  4. Follows best practices while avoiding common pitfalls

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Adding a New Skill

  1. Create a directory under the appropriate category
  2. Add a SKILL.md following our template
  3. Include practical examples and best practices
  4. Submit a pull request

License

MIT License - See LICENSE for details.

Related Projects


Built for developers, by developers, with Claude

Details

Marketplace
miles990/claude-software-skills
Source
tools-integrations/claude-code-sdk
Category
Community
Listed since
Apr 6, 2026

More from miles990/claude-software-skills

All 56

Similar to claude-code-sdk

More AI Agents & LLM Apps