[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KVW73XFRXAPQTJMCZ2957T":3,"skill-same:01M6KVW73XFRXAPQTJMCZ2957T":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":6,"updatedAt":52,"install":53,"resources":66},"01M6KVW73XFRXAPQTJMCZ2957T","claude-sdk-deployment",null,"Deploying Claude Agent SDK agents to production — wrapping the SDK in FastAPI with SSE streaming, session resume, cost tracking via ResultMessage, Docker\u002FRailway\u002FFly config, ANTHROPIC_API_KEY handling, and bearer-auth patterns. Read when going from \"it works locally\" to \"it's running on a server\", when designing the request\u002Fresponse contract for an agent endpoint, or when investigating why deployments are slower or more expensive than expected.","Folken2\u002Fnuvel","Folken2","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F175213316?v=4","01M6KVPA04RKNPCC04H2G96FAS","Albert Folch","01M6KVPA43VNTA4PXSEB1TCD81",2,"MIT","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Fnuvel\u002Fbackends\u002Fclaude_agent_sdk\u002Fskills\u002Fclaude-sdk-deployment\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"claude sdk deployment","deployment","sdk","read","request","session resume","for","Railway","agent sdk","patterns","sse streaming","fastapi","why","fly","api","endpoint","server","streaming","config","auth","2026-11-10 10:12:30",false,"---\nname: claude-sdk-deployment\ndescription: Deploying Claude Agent SDK agents to production — wrapping the SDK in FastAPI with SSE streaming, session resume, cost tracking via ResultMessage, Docker\u002FRailway\u002FFly config, ANTHROPIC_API_KEY handling, and bearer-auth patterns. Read when going from \"it works locally\" to \"it's running on a server\", when designing the request\u002Fresponse contract for an agent endpoint, or when investigating why deployments are slower or more expensive than expected.\n---\n\n# Deploying a Claude Agent SDK agent\n\nThe SDK gives you `ClaudeSDKClient`, which is async-context-manager + async-iterator. It does not give you a server. The two questions deployment answers:\n\n1. **What's the request\u002Fresponse contract?** (HTTP path, auth, streaming format)\n2. **What does the server do with the SDK?** (per-request client, session state, cost tracking)\n\nThe nuvel-scaffolded `server.py` answers both with a FastAPI + SSE shape that's familiar to people who've deployed ADK or other agent runtimes. This skill explains why that shape was chosen and how to extend it.\n\n## The default scaffold's contract\n\n```\nPOST \u002Frun_sse\u002F\nAuthorization: Bearer \u003CAPI_KEY>      (if API_KEY env is set)\nContent-Type: application\u002Fjson\n{ \"prompt\": \"...\" }\n\nResponse: text\u002Fevent-stream\ndata: {\"type\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"...\"}]}\ndata: {\"type\": \"assistant\", \"content\": [{\"type\": \"tool_use\", \"name\": \"...\", \"input\": {...}}]}\ndata: {\"type\": \"result\", \"session_id\": \"...\", \"total_cost_usd\": 0.0042, \"duration_ms\": 4200, \"num_turns\": 3}\ndata: [DONE]\n```\n\nEach SSE event is one Claude SDK message serialized as JSON. The frontend can render text incrementally, surface tool calls as they happen, and capture cost on the final `result` event.\n\n## One client per request\n\nDon't reuse a single `ClaudeSDKClient` across requests. The async context manager is the unit of session — entering it starts a session, exiting it tears down the subprocess transport and any MCP server children. Build a fresh client per request:\n\n```python\nasync def _sse_stream(prompt: str):\n    async with get_client() as client:\n        await client.query(prompt)\n        async for msg in client.receive_response():\n            yield serialize(msg)\n```\n\nCosts about 100ms of startup per request. If that matters for your latency budget, you'll want a client pool — but most agents are several-second responses where 100ms doesn't move the needle.\n\n## Session resume (multi-turn from a stateless server)\n\nA stateless HTTP server can still run multi-turn agents by threading `session_id`:\n\n```python\n@app.post(\"\u002Frun_sse\u002F\")\nasync def run_sse(body: dict):\n    options = build_options()\n    options.resume = body.get(\"session_id\")  # None on first turn\n    options.fork_session = False              # continue, don't fork\n\n    async with ClaudeSDKClient(options=options) as client:\n        await client.query(body[\"prompt\"])\n        async for msg in client.receive_response():\n            yield serialize(msg)\n```\n\nThe frontend keeps the `session_id` from the `result` event of turn N and sends it in turn N+1. The SDK loads conversation history transparently.\n\nFor multi-tenant deployments where session storage shouldn't live on the SDK's filesystem, use `session_store` with a `PostgresSessionStore` or similar — the SDK exposes a session-store interface for this.\n\n## Cost tracking\n\nThe `ResultMessage` at the end of every turn includes `total_cost_usd` (cumulative for the session) and `num_turns`. Two patterns:\n\n**Per-turn cost** = `total_cost_usd_now - total_cost_usd_previous_turn`. Subtract across turns yourself if you want per-turn billing.\n\n**Per-session cap** = `max_budget_usd` in `ClaudeAgentOptions`. The SDK enforces it; once exceeded, further LLM calls fail. No plugin needed.\n\n**Per-tenant aggregation** = persist the `result` event to a tracing table (the nuvel scaffold writes JSONL via `traces\u002Ftrace_writer.py`) and aggregate at query time. Real production systems use a `total_cost_usd` column on a `sessions` table updated on each turn.\n\nDon't try to match LiteLLM-style per-call pricing — the SDK gives you cumulative cost per session and that's enough for 95% of cases.\n\n## ANTHROPIC_API_KEY handling\n\nThe SDK reads `ANTHROPIC_API_KEY` from the environment. You don't pass it explicitly; the underlying CLI does the lookup. Two operational patterns:\n\n**Single-key deploys** — set `ANTHROPIC_API_KEY` in the deployment env (Railway dashboard, Fly secrets, etc.). The agent uses one key for all users.\n\n**Per-tenant keys** — set `env={\"ANTHROPIC_API_KEY\": tenant_key}` in `ClaudeAgentOptions`. The SDK launches its subprocess transport with that env, so each session uses its own key. Right when you're charging tenants directly.\n\n## Bearer auth on \u002Frun_sse\u002F\n\nThe scaffold's pattern: if `API_KEY` env is set, require `Authorization: Bearer \u003CAPI_KEY>`. If unset, no auth (good for local dev). Don't reach for OAuth or JWT until you have a real reason — most internal-tool agents are fine with a single shared bearer behind a VPN or Cloudflare Access.\n\nWhen you do need real auth (multi-tenant, public), put it in front of the FastAPI app — not inside it. Cloudflare Access, an API gateway, or a simple JWT-validating proxy are all better than building auth into the agent server.\n\n## Docker + Railway + Fly\n\nThe scaffold ships with `Dockerfile` (python:3.12-slim, copies the project, runs `python server.py`) and `railway.json` (starts via the Dockerfile, healthcheck on `\u002Fhealth`). For Fly, drop a `fly.toml` next to it; the Dockerfile is portable.\n\nOne Docker subtlety: the Claude Agent SDK spawns a Node.js subprocess (the underlying CLI). The slim base image works because `claude-agent-sdk` ships its own bundled Node — but if you switch to `python:3.12-alpine` you'll likely hit glibc issues. Stay on slim.\n\n## Common deployment mistakes\n\n- **Reusing a single `ClaudeSDKClient` across HTTP requests.** Eventually leaks subprocesses or stalls. Always per-request.\n- **Forgetting `permission_mode`.** Default is `default` (interactive). Server deploys need `acceptEdits` or `dontAsk`. See `claude-sdk-permissions`.\n- **No `max_budget_usd`.** A bug or prompt injection can cause runaway costs. Set a per-session cap; it's free and prevents disasters.\n- **Sending tool internals to the client.** Serialize tool args carefully — they sometimes contain secrets (API keys, file contents) that shouldn't reach the browser.\n- **Using `bypassPermissions` to skip prompts.** Lock-down with `dontAsk` + explicit `allowed_tools` instead.\n\n## Quick checklist\n\nBefore merging a Claude Agent SDK agent to production:\n\n- [ ] `permission_mode` is `acceptEdits` or `dontAsk`, not `default`\n- [ ] `max_budget_usd` is set\n- [ ] `ANTHROPIC_API_KEY` is in the deploy environment, not committed\n- [ ] `API_KEY` is set if `\u002Frun_sse\u002F` is internet-facing\n- [ ] `\u002Fhealth` returns 200 and is wired to the platform's healthcheck\n- [ ] Trace writer is on (`TRACE_ENABLED=true`) so you can debug after the fact\n- [ ] One `ClaudeSDKClient` per request, not a singleton\n","# Deploying a Claude Agent SDK agent\n\nThe SDK gives you `ClaudeSDKClient`, which is async-context-manager + async-iterator. It does not give you a server. The two questions deployment answers:\n\n1. **What's the request\u002Fresponse contract?** (HTTP path, auth, streaming format)\n2. **What does the server do with the SDK?** (per-request client, session state, cost tracking)\n\nThe nuvel-scaffolded `server.py` answers both with a FastAPI + SSE shape that's familiar to people who've deployed ADK or other agent runtimes. This skill explains why that shape was chosen and how to extend it.\n\n## The default scaffold's contract\n\n```\nPOST \u002Frun_sse\u002F\nAuthorization: Bearer \u003CAPI_KEY>      (if API_KEY env is set)\nContent-Type: application\u002Fjson\n{ \"prompt\": \"...\" }\n\nResponse: text\u002Fevent-stream\ndata: {\"type\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"...\"}]}\ndata: {\"type\": \"assistant\", \"content\": [{\"type\": \"tool_use\", \"name\": \"...\", \"input\": {...}}]}\ndata: {\"type\": \"result\", \"session_id\": \"...\", \"total_cost_usd\": 0.0042, \"duration_ms\": 4200, \"num_turns\": 3}\ndata: [DONE]\n```\n\nEach SSE event is one Claude SDK message serialized as JSON. The frontend can render text incrementally, surface tool calls as they happen, and capture cost on the final `result` event.\n\n## One client per request\n\nDon't reuse a single `ClaudeSDKClient` across requests. The async context manager is the unit of session — entering it starts a session, exiting it tears down the subprocess transport and any MCP server children. Build a fresh client per request:\n\n```python\nasync def _sse_stream(prompt: str):\n    async with get_client() as client:\n        await client.query(prompt)\n        async for msg in client.receive_response():\n            yield serialize(msg)\n```\n\nCosts about 100ms of startup per request. If that matters for your latency budget, you'll want a client pool — but most agents are several-second responses where 100ms doesn't move the needle.\n\n## Session resume (multi-turn from a stateless server)\n\nA stateless HTTP server can still run multi-turn agents by threading `session_id`:\n\n```python\n@app.post(\"\u002Frun_sse\u002F\")\nasync def run_sse(body: dict):\n    options = build_options()\n    options.resume = body.get(\"session_id\")  # None on first turn\n    options.fork_session = False              # continue, don't fork\n\n    async with ClaudeSDKClient(options=options) as client:\n        await client.query(body[\"prompt\"])\n        async for msg in client.receive_response():\n            yield serialize(msg)\n```\n\nThe frontend keeps the `session_id` from the `result` event of turn N and sends it in turn N+1. The SDK loads conversation history transparently.\n\nFor multi-tenant deployments where session storage shouldn't live on the SDK's filesystem, use `session_store` with a `PostgresSessionStore` or similar — the SDK exposes a session-store interface for this.\n\n## Cost tracking\n\nThe `ResultMessage` at the end of every turn includes `total_cost_usd` (cumulative for the session) and `num_turns`. Two patterns:\n\n**Per-turn cost** = `total_cost_usd_now - total_cost_usd_previous_turn`. Subtract across turns yourself if you want per-turn billing.\n\n**Per-session cap** = `max_budget_usd` in `ClaudeAgentOptions`. The SDK enforces it; once exceeded, further LLM calls fail. No plugin needed.\n\n**Per-tenant aggregation** = persist the `result` event to a tracing table (the nuvel scaffold writes JSONL via `traces\u002Ftrace_writer.py`) and aggregate at query time. Real production systems use a `total_cost_usd` column on a `sessions` table updated on each turn.\n\nDon't try to match LiteLLM-style per-call pricing — the SDK gives you cumulative cost per session and that's enough for 95% of cases.\n\n## ANTHROPIC_API_KEY handling\n\nThe SDK reads `ANTHROPIC_API_KEY` from the environment. You don't pass it explicitly; the underlying CLI does the lookup. Two operational patterns:\n\n**Single-key deploys** — set `ANTHROPIC_API_KEY` in the deployment env (Railway dashboard, Fly secrets, etc.). The agent uses one key for all users.\n\n**Per-tenant keys** — set `env={\"ANTHROPIC_API_KEY\": tenant_key}` in `ClaudeAgentOptions`. The SDK launches its subprocess transport with that env, so each session uses its own key. Right when you're charging tenants directly.\n\n## Bearer auth on \u002Frun_sse\u002F\n\nThe scaffold's pattern: if `API_KEY` env is set, require `Authorization: Bearer \u003CAPI_KEY>`. If unset, no auth (good for local dev). Don't reach for OAuth or JWT until you have a real reason — most internal-tool agents are fine with a single shared bearer behind a VPN or Cloudflare Access.\n\nWhen you do need real auth (multi-tenant, public), put it in front of the FastAPI app — not inside it. Cloudflare Access, an API gateway, or a simple JWT-validating proxy are all better than building auth into the agent server.\n\n## Docker + Railway + Fly\n\nThe scaffold ships with `Dockerfile` (python:3.12-slim, copies the project, runs `python server.py`) and `railway.json` (starts via the Dockerfile, healthcheck on `\u002Fhealth`). For Fly, drop a `fly.toml` next to it; the Dockerfile is portable.\n\nOne Docker subtlety: the Claude Agent SDK spawns a Node.js subprocess (the underlying CLI). The slim base image works because `claude-agent-sdk` ships its own bundled Node — but if you switch to `python:3.12-alpine` you'll likely hit glibc issues. Stay on slim.\n\n## Common deployment mistakes\n\n- **Reusing a single `ClaudeSDKClient` across HTTP requests.** Eventually leaks subprocesses or stalls. Always per-request.\n- **Forgetting `permission_mode`.** Default is `default` (interactive). Server deploys need `acceptEdits` or `dontAsk`. See `claude-sdk-permissions`.\n- **No `max_budget_usd`.** A bug or prompt injection can cause runaway costs. Set a per-session cap; it's free and prevents disasters.\n- **Sending tool internals to the client.** Serialize tool args carefully — they sometimes contain secrets (API keys, file contents) that shouldn't reach the browser.\n- **Using `bypassPermissions` to skip prompts.** Lock-down with `dontAsk` + explicit `allowed_tools` instead.\n\n## Quick checklist\n\nBefore merging a Claude Agent SDK agent to production:\n\n- [ ] `permission_mode` is `acceptEdits` or `dontAsk`, not `default`\n- [ ] `max_budget_usd` is set\n- [ ] `ANTHROPIC_API_KEY` is in the deploy environment, not committed\n- [ ] `API_KEY` is set if `\u002Frun_sse\u002F` is internet-facing\n- [ ] `\u002Fhealth` returns 200 and is wired to the platform's healthcheck\n- [ ] Trace writer is on (`TRACE_ENABLED=true`) so you can debug after the fact\n- [ ] One `ClaudeSDKClient` per request, not a singleton\n",{"name":5,"description":7},"main","41d246dd855999c6bc4be528bc8d0d1b10ac8c47","nuvel\u002Fbackends\u002Fclaude_agent_sdk\u002Fskills\u002Fclaude-sdk-deployment",1,"https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel","https:\u002F\u002Ffolken2.github.io\u002Fnuvel\u002F","https:\u002F\u002Fgithub.com\u002FFolken2","folch.ai","2026-11-05 22:40:38",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add Folken2\u002Fnuvel --skill claude-sdk-deployment",{"tool":59,"command":60},"bunx","bunx skills add Folken2\u002Fnuvel --skill claude-sdk-deployment",{"tool":62,"command":63},"pnpm","pnpm dlx skills add Folken2\u002Fnuvel --skill claude-sdk-deployment","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Fnuvel\u002Fbackends\u002Fclaude_agent_sdk\u002Fskills\u002Fclaude-sdk-deployment\u002FSKILL.md",true,[],[68,77,89,110,126,140],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":39},"01M6KVZNJQ7AVMVBS205404CS7","greet","Greet a user warmly by name.","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Ftests\u002Ftest_agent_plugins\u002Ffixtures\u002Fvalid-full\u002Fskills\u002Fgreet\u002FSKILL.md",[],[70,75,76],"user","name",{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":39},"01M6KVZHYK2C9S5GRM3PZAFDXG","hello","A simple hello skill that survives a broken mcp.json.","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Ftests\u002Ftest_agent_plugins\u002Ffixtures\u002Fbad-mcp\u002Fskills\u002Fhello\u002FSKILL.md",[],[79,84,85,86,87,88],"MCP","hello skill","json","broken","simple",{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":39},"01M6KVZC94REQZ852EJ99ZXATK","grok-workflows","Prompt templates and workflows for using xAI GrokBot with Nuvel — code, design, research, and automated pipelines.","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Fplugins\u002Fgrokbot-plugin\u002Fskills\u002Fgrok-workflows\u002FSKILL.md",[],[96,97,98,99,100,101,102,103,104,105,106,107,108,25,109],"workflows","grok","grok workflows","design","research","prompt","prompt templates","code","templates","xai","grokbot","pipelines","with","nuvel",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":39},"01M6KVZ7BA5MJ1N614MTP2JXCQ","grok-setup","Configure xAI GrokBot with Nuvel API integration and project context for Nuvel-aligned development.","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Fplugins\u002Fgrokbot-plugin\u002Fskills\u002Fgrok-setup\u002FSKILL.md",[],[97,117,118,25,108,119,109,120,121,122,106,123,124,33,105,125],"grok setup","setup","project","project context","api integration","configure","development","integration","context",{"skillNo":127,"name":128,"nameZh":6,"description":129,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":39},"01M6KVZ3WYQ6V6XVCRE77WT2WY","cursor-setup","Configure Cursor IDE with Nuvel rules, MCP server integration, and project settings for OrgMemory-aware development.","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Fplugins\u002Fcursor-plugin\u002Fskills\u002Fcursor-setup\u002FSKILL.md",[],[133,134,118,124,84,135,123,35,136,122,137,138,119,108,25,139,109],"cursor","cursor setup","mcp server","ide","Rules","settings","project settings",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":39},"01M6KVZ0GGSJM4AC8PK7G53H85","cursor-review","Use Cursor IDE with Nuvel OrgMemory to review changes — diff analysis, standards checking, and pre-commit review.","https:\u002F\u002Fgithub.com\u002FFolken2\u002Fnuvel\u002Fblob\u002Fmain\u002Fplugins\u002Fcursor-plugin\u002Fskills\u002Fcursor-review\u002FSKILL.md",[],[147,133,148,149,150,151,152,136,153,154,155,108,156,157,109],"cursor review","review","commit","review changes","pre-commit","analysis","use","diff","standards","changes","diff analysis"]