
comfy-sdk
Guidance for coding agents building apps with the Comfy SDK and Comfy Router. No MCP server.
- GitHub stars
- 262
Install
/plugin install comfy-sdk@comfy-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add Comfy-Org/comfy-skills.
Contents
Discovered from sourceSkills 1
comfy-sdk — build with Comfy Router
Steering only. Model names, schemas, prices and default timeouts change: discover them at run time (section 3) or read them off the installed SDK, and never paste one from memory.
1. Pick the right client
- Router (partner models,
https://api.comfy.org) is reached through themodelsnamespace:- Python:
Comfy().models(AsyncComfy().modelsfor asyncio). - TypeScript: the module-level
comfy.models, aftercomfy.config({ credentials })or withCOMFY_API_KEYset.new Comfy({ apiKey })is the Comfy Cloud workflow client and has no.models.
- Python:
- Cloud (
/api/v2/jobs, run a ComfyUI workflow) is the class client in both SDKs. - Both use the same
COMFY_API_KEY. Hosts are separate:COMFY_ROUTER_BASE_URLredirects Router,COMFY_BASE_URLredirects Cloud. Leave both unset in production.
from comfy_sdk import Comfy
client = Comfy() # reads COMFY_API_KEY
result = client.models.run("<provider>/<model>", {<provider's native body>})
import { comfy } from "@comfyorg/sdk";
comfy.config({ credentials: process.env.COMFY_API_KEY });
const { kind, data, requestId } = await comfy.models.run("<provider>/<model>", {<native body>});
2. Credentials stay on the server
- The SDKs read
COMFY_API_KEYfrom the process environment; neither loads a.envfile. Your framework does that (python-dotenv, Next.js.env.local, etc.). An explicitapi_key=/credentialsargument always wins over the variable. - Never expose the key to a browser bundle (no
NEXT_PUBLIC_/VITE_prefix). Call Router from a server route and return the result to the page. - Preflight before any paid call: list models (section 3). A
401there means the key, not the model, is wrong.
3. Discover, then call
GET /v2/modelslists what the credential can run, with billing facts. Paginate withnext_cursorwhilehas_moreis true; treat cursors as opaque.GET /v2/models/{provider}/{model}/openapi.jsonis that model's input/output schema. The second argument torun/submitis the provider's native body, forwarded unchanged, so build it from this schema, not from another provider's shape.- TypeScript wraps both:
comfy.models.list()walks the catalog andcomfy.models.schema(model)fetches the document. In Python, if the installedclient.modelshas no such helper, call the two routes on the Router host yourself withAuthorization: Bearer <COMFY_API_KEY>. - A model id is exactly two segments,
provider/model.
4. run, submit or subscribe
runblocks until the generation is finished. The wait is server side: Router holds the connection up to its own deadline, then answers504 deadline_exceeded. The SDK retries that with the sameIdempotency-KeyandRetry-After, collecting the running generation rather than starting a second one.submitreturns a handle with arequest_idat once. Use it in any web request handler, serverless function or job queue that cannot hold a connection for minutes. Collect later, even from another process, withmodels.handle(model, request_id)thenget()/status()/cancel().subscribeis submit + poll + collect with a progress callback. Its timeout is client side only; when it expires it makes one best-effort cancel. A generation already running at the partner completes and is billed regardless.- There are no webhooks or push events: the status route is how you follow a
request.
submit/handle/subscribeneedcomfy-sdk/@comfyorg/sdk0.3.0 or newer.
5. Timeouts: units and what they bound
- Python
models.run(..., timeout=)is seconds and defaults to the SDK's own run timeout, sized to Router's deadline.Comfy(timeout=...)sizes ordinary API calls and does not change the run default. - TypeScript
{ timeoutMs }is milliseconds; its default is longer than Router's deadline so a same-key collect still fits. Prefer anAbortSignaltotimeoutMs: null. - The exact defaults move between releases. Read them from the installed SDK
(the
runsignature,DEFAULT_RUN_TIMEOUT_MS) instead of hard-coding a number. - Do not set a run timeout below a realistic generation (tens of seconds to
minutes). If your platform caps request duration (serverless, proxies), switch
to
submitinstead of lowering the timeout.
6. Retries and idempotency are already handled
- Every
run/submitmints anIdempotency-Keyand reuses it for its own retries, so a retried attempt is charged at most once. Callingrunagain is a new key and a new charge: do not wrap it in your own retry loop. - To retry one logical call across processes or restarts, pass
idempotency_key=/{ idempotencyKey }yourself and keep the body identical; the same key with a different body is refused409 invalid_input(use a new key).
7. Errors: branch on the bucket
A Router error response carries Router's wire bucket (also the
X-Comfy-Error-Type header), but where you read it depends on the language and
the call:
- Python, every call: Router responses raise classes from
comfy_sdk.router_exceptions, all descending fromRouterError; readexc.error_type. - TypeScript
comfy.models.run(synchronous): throwsComfyErrorand its subclasses (InsufficientCredits,Forbidden,Unauthorized,NotFound), notrouterErrors.*. Readerr.code; there is noerrorType, andinstanceof routerErrors.RouterErrorisfalse. - TypeScript queued (
submit/handle/subscribe): a Router error response throwsrouterErrors.*, all descending fromrouterErrors.RouterError; readerr.errorType.
Failures on the client side are not Router responses and carry no bucket:
- SDK-raised: a plain
ComfyError(Python and TypeScript). An unreadable reply iscodeinvalid_responsein Python and on the TypeScript queued calls, butunexpected_responsefrom TypeScriptcomfy.models.run. A TypeScript queued call exceedingtimeoutMsisrequest_timeout. - Transport: a dropped connection or read timeout surfaces as the HTTP library's
own error once the SDK's retries are spent:
httpx.HTTPErrorin Python, a nativeTypeErrorfromfetchin TypeScript. - Waits and cancellation: Python
subscribepast itstimeout=raisesTimeoutError(arunpast itstimeout=is a transport read timeout). A TypeScript caller's ownAbortSignalrethrows its abort reason unchanged (anAbortErrorby default).
So a TypeScript app needs a ComfyError catch on both paths, a
routerErrors.RouterError catch on the queued one, and a final catch for
transport errors and its own aborts; a Python app catches RouterError, then
ComfyError, httpx.HTTPError and TimeoutError.
insufficient_credits(402): stop and tell the user to add credits. Never retry.content_policy_violation: do not resend the same prompt.rate_limited/concurrency_limit_exceeded(429): waitRetry-After, then resend. Pythonrundoes this for you. TypeScript does not retry a429; waiterr.retryAfterseconds yourself, or tell the user to try again.not_enabled(403): the workspace is not on this model or route yet; terminal.provider_timeoutvsdeadline_exceeded: both504; the first is the partner, the second is Comfy's bound. The SDK retries the second with the same key.- Keep a catch-all branch. An unrecognised bucket surfaces as the base class:
RouterErrorin Python and for Router responses on the TypeScript queued path,ComfyErrorfrom TypeScriptrunand from SDK-raised client-side failures. - A queued request can finish as
COMPLETEDwith anerror_type;get()raises the typed error, and the event iterator yields it as the last observation.
8. Results
- Python
runreturns the provider's payload as-is. TypeScript returns{ kind, data, requestId }(kindis"json"or"binary"; branch on it) and caps the buffered body (maxBytes). - Asset URLs in a result are time-limited. Download or re-host what you want to keep before responding to the user; do not store a partner URL as a permanent link.
9. Before the first generation
- Key read server side;
GET /v2/modelssucceeds. - Model chosen from that list; body built from its
openapi.json. runonly where the process can wait minutes; otherwisesubmit.- Timeout in the right unit, or left at the default.
insufficient_creditssurfaced to the user, not retried.
Read next
- Quickstart: https://docs.comfy.org/development/comfy-router/quickstart
- Queued delivery: https://docs.comfy.org/development/comfy-router/queue
- Error buckets: https://docs.comfy.org/development/comfy-router/reference#error-buckets
- SDK READMEs: https://github.com/Comfy-Org/comfy-python-sdk and https://github.com/Comfy-Org/comfy-typescript-sdk
Sponsors
Details
- Marketplace
- Comfy-Org/comfy-skills
- Source
- claude-code-sdk
- Category
- Community