novelai_image_mcp.nai — NovelAI HTTP クライアント¶
nai/ サブパッケージは NovelAI の HTTP クライアントです。MCP に依存しません —
MCP サーバーとは独立して、任意の非同期 Python コードから単体で利用できます。
サブモジュール¶
novelai_image_mcp.nai.client¶
高レベルの非同期クライアント。ワイヤーフォーマットのエンコーダー
(payload.build_generation_payload)とレスポンスデコーダー
(response.parse_messagepack_images)を、共有の
httpx.AsyncClient 上でラップします。
Complete NovelAI HTTP client built on a shared httpx async session.
A long-lived httpx.AsyncClient is owned by the instance (or supplied by the
MCP lifespan) and used for all NovelAI API traffic. Covers generation, Director,
utility, and account business logic.
- exception novelai_image_mcp.nai.client.MissingNovelAITokenError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIAuthenticationErrorNo usable NovelAI credential is configured.
- class novelai_image_mcp.nai.client.NovelAIClient(credentials, *, http_client=None, image_base_url='https://image.novelai.net', account_base_url='https://image.novelai.net', legacy_image_base_url='https://api.novelai.net', timeout=120.0, vibe_cache_entries=64)[ソース]¶
ベースクラス:
objectProject-owned client for generation, tools, utilities, and account APIs.
- パラメータ:
- async generate(request)[ソース]¶
- パラメータ:
request (GenerationRequest)
- 戻り値の型:
tuple[NovelAIImage, ...]
- async stream_generation(request)[ソース]¶
Yield V4 / V4.5 / V5 events as the active driver produces chunks.
- パラメータ:
request (GenerationRequest)
- 戻り値の型:
- async director(tool, image, *, prompt='', defry=0, emotion=None, emotion_level=EmotionLevel.NORMAL)[ソース]¶
- パラメータ:
tool (DirectorTool)
image (bytes)
prompt (str)
defry (int)
emotion (Emotion | None)
emotion_level (EmotionLevel)
- 戻り値の型:
- async upscale(image, *, factor=4, model=None)[ソース]¶
Upscale an image 4x with NovelAI's standalone upscaler.
The endpoint lives on image.novelai.net and takes {image, model, declared_blur_sigma}. It is 4x only — the API exposes no scaling factor — and only the V5 line supports standalone upscaling, so model defaults to the V5 full model (see NovelAISettings.upscale_model).
Verified live on 2026-10-10: V3 / V4 / V4.5 (including their inpainting and curated variants) are rejected with "model ... doesn't support standalone upscaling".
- パラメータ:
- 戻り値の型:
- async annotate(image, model)[ソース]¶
- パラメータ:
image (bytes)
model (ControlNetModel)
- 戻り値の型:
- exception novelai_image_mcp.nai.client.NovelAIError(message, *, code=None, explanation=None)¶
ベースクラス:
ExceptionBase class for NovelAI failures.
codeis the NovelAI error code when known (Nonefor transport, timeout, or local validation failures that carry no server code);explanationis NovelAI's official explanation for documented codes.
- exception novelai_image_mcp.nai.client.NovelAIProviderError(message, *, code=None, explanation=None)¶
ベースクラス:
NovelAIErrorNovelAI rejected or failed the request.
- exception novelai_image_mcp.nai.client.NovelAIResponseError(message, *, code=None, explanation=None)¶
ベースクラス:
NovelAIErrorNovelAI returned malformed or unsupported data.
- exception novelai_image_mcp.nai.client.NovelAITimeoutError(message, *, code=None, explanation=None)¶
ベースクラス:
NovelAIErrorA request exceeded its timeout.
- exception novelai_image_mcp.nai.client.NovelAITransportError(message, *, code=None, explanation=None)¶
ベースクラス:
NovelAIErrorThe request could not reach NovelAI.
- async novelai_image_mcp.nai.client.generate_image_from_plan(plan, *, client, n_samples=1, quality=True, uc_preset=0, noise_schedule='karras', cfg_rescale=0.0, dynamic_thresholding=False, auto_smea=False, prefer_brownian=True)[ソース]¶
Generate a single image from a high-level plan (used by the sync CLI).
The caller supplies the configured client plus the generation defaults (read from settings, not from a global config).
novelai_image_mcp.nai.constants¶
NovelAI API サーフェスの enum: Action、Model、Sampler、
DirectorTool、Emotion、EmotionLevel、ControlNetModel、Endpoint、
NoiseSchedule。さらに述語 is_v4_model、is_v5_model、
supports_vibe、is_inpaint_model。
NovelAI protocol constants and model capability helpers.
- class novelai_image_mcp.nai.constants.IntEnum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
-
Enum where members are also (and must be) ints
- class novelai_image_mcp.nai.constants.StrEnum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
-
Enum where members are also (and must be) strings
- __new_member__(*values)¶
values must already be of type str
- class novelai_image_mcp.nai.constants.Endpoint(*values)[ソース]¶
ベースクラス:
StrEnumNovelAI API path constants.
Most paths are rooted at
https://image.novelai.net(the consolidated third-party host),UPSCALE(/ai/upscale, V5 models only) included.ANNOTATEis the one exception:/ai/annotate-imagewas never migrated and remains on the Primary API athttps://api.novelai.net. The Primary API's docs (https://api.novelai.net/docs/) state that third-party users may use its/ai/routes. SeeNovelAIClient.legacy_image_base_url.The
/ai/generate-imagefamily is split by model generation:IMAGE(/ai/generate-image) — used by V3 / Furry legacy models. Returns a ZIP archive (application/zip) with HTTP 201.IMAGE_STREAM(/ai/generate-image-stream) — used by V4 / V4.5 / V5 new models. Returns a MessagePack stream (stream: "msgpack") with HTTP 200. The selection is driven byis_v4_modelinclient.py.
- LOGIN = '/user/login'¶
- USER_DATA = '/user/data'¶
- SUBSCRIPTION = '/user/subscription'¶
- IMAGE = '/ai/generate-image'¶
- IMAGE_STREAM = '/ai/generate-image-stream'¶
- DIRECTOR = '/ai/augment-image'¶
- ENCODE_VIBE = '/ai/encode-vibe'¶
- UPSCALE = '/ai/upscale'¶
- ANNOTATE = '/ai/annotate-image'¶
- SUGGEST_TAGS = '/ai/generate-image/suggest-tags'¶
- class novelai_image_mcp.nai.constants.Model(*values)[ソース]¶
ベースクラス:
StrEnum- V3 = 'nai-diffusion-3'¶
- V3_INPAINT = 'nai-diffusion-3-inpainting'¶
- FURRY = 'nai-diffusion-furry-3'¶
- FURRY_INPAINT = 'nai-diffusion-furry-3-inpainting'¶
- V4 = 'nai-diffusion-4-full'¶
- V4_INPAINT = 'nai-diffusion-4-full-inpainting'¶
- V4_CURATED = 'nai-diffusion-4-curated-preview'¶
- V4_CURATED_INPAINT = 'nai-diffusion-4-curated-inpainting'¶
- V4_5 = 'nai-diffusion-4-5-full'¶
- V4_5_INPAINT = 'nai-diffusion-4-5-full-inpainting'¶
- V4_5_CURATED = 'nai-diffusion-4-5-curated'¶
- V4_5_CURATED_INPAINT = 'nai-diffusion-4-5-curated-inpainting'¶
- V5 = 'nai-diffusion-5-full'¶
- V5_CURATED = 'nai-diffusion-5-curated'¶
- V5_INPAINT = 'nai-diffusion-5-full-inpainting'¶
- class novelai_image_mcp.nai.constants.Action(*values)[ソース]¶
ベースクラス:
StrEnum- GENERATE = 'generate'¶
- IMG2IMG = 'img2img'¶
- INPAINT = 'infill'¶
- class novelai_image_mcp.nai.constants.Sampler(*values)[ソース]¶
ベースクラス:
StrEnum- EULER = 'k_euler'¶
- EULER_ANCESTRAL = 'k_euler_ancestral'¶
- DPM_2S_ANCESTRAL = 'k_dpmpp_2s_ancestral'¶
- DPM_2M = 'k_dpmpp_2m'¶
- DPM_2M_SDE = 'k_dpmpp_2m_sde'¶
- DPM_SDE = 'k_dpmpp_sde'¶
- DDIM = 'ddim_v3'¶
- class novelai_image_mcp.nai.constants.NoiseSchedule(*values)[ソース]¶
ベースクラス:
StrEnum- NATIVE = 'native'¶
- KARRAS = 'karras'¶
- EXPONENTIAL = 'exponential'¶
- POLYEXPONENTIAL = 'polyexponential'¶
- class novelai_image_mcp.nai.constants.ControlNetModel(*values)[ソース]¶
ベースクラス:
StrEnum- PALETTE_SWAP = 'hed'¶
- FORM_LOCK = 'midas'¶
- SCRIBBLER = 'fake_scribble'¶
- BUILDING_CONTROL = 'mlsd'¶
- LANDSCAPER = 'uniformer'¶
- class novelai_image_mcp.nai.constants.DirectorTool(*values)[ソース]¶
ベースクラス:
StrEnum- LINE_ART = 'lineart'¶
- SKETCH = 'sketch'¶
- BACKGROUND_REMOVAL = 'bg-removal'¶
- DECLUTTER = 'declutter'¶
- COLORIZE = 'colorize'¶
- EMOTION = 'emotion'¶
- class novelai_image_mcp.nai.constants.Emotion(*values)[ソース]¶
ベースクラス:
StrEnum- NEUTRAL = 'neutral'¶
- HAPPY = 'happy'¶
- SAD = 'sad'¶
- ANGRY = 'angry'¶
- SCARED = 'scared'¶
- SURPRISED = 'surprised'¶
- TIRED = 'tired'¶
- EXCITED = 'excited'¶
- NERVOUS = 'nervous'¶
- THINKING = 'thinking'¶
- CONFUSED = 'confused'¶
- SHY = 'shy'¶
- DISGUSTED = 'disgusted'¶
- SMUG = 'smug'¶
- BORED = 'bored'¶
- LAUGHING = 'laughing'¶
- IRRITATED = 'irritated'¶
- AROUSED = 'aroused'¶
- EMBARRASSED = 'embarrassed'¶
- WORRIED = 'worried'¶
- LOVE = 'love'¶
- DETERMINED = 'determined'¶
- HURT = 'hurt'¶
- PLAYFUL = 'playful'¶
- class novelai_image_mcp.nai.constants.EmotionLevel(*values)[ソース]¶
ベースクラス:
IntEnum- NORMAL = 0¶
- SLIGHTLY_WEAK = 1¶
- WEAK = 2¶
- EVEN_WEAKER = 3¶
- VERY_WEAK = 4¶
- WEAKEST = 5¶
- novelai_image_mcp.nai.constants.is_v4_model(model)[ソース]¶
True for structured-prompt (V4+) models: V4 / V4.5 / V5 families.
These use the
/ai/generate-image-streamendpoint (MessagePack) and thev4_prompt/v4_negative_promptcaption payload shape. The name is retained for backward compatibility (publicnaiAPI).
- novelai_image_mcp.nai.constants.is_v5_model(model)[ソース]¶
True for NovelAI Diffusion V5 models (Full / Curated / Inpainting).
- novelai_image_mcp.nai.constants.supports_vibe(model)[ソース]¶
True when vibe transfer (reference images) works for this model.
Vibe transfer is available on V4 / V4.5 only — V3 / Furry and V5 (feature not yet released for V5 per the official announcement) return False.
- novelai_image_mcp.nai.constants.UPSCALE_MODELS = frozenset({Model.V5_CURATED, Model.V5})¶
Models the standalone upscaler accepts. Live-verified 2026-10-10 against POST https://image.novelai.net/ai/upscale: the V5 line returns 200 while every V3 / V4 / V4.5 variant (inpainting and curated included) is rejected with "model ... doesn't support standalone upscaling".
- novelai_image_mcp.nai.constants.supports_upscale(model)[ソース]¶
True when the standalone /ai/upscale endpoint accepts this model.
- novelai_image_mcp.nai.constants.params_version_for(model)[ソース]¶
Return the NovelAI
params_versionfor a model.V5 clients ship both
3(Marinara-Engine) and4(Auto-NovelAI, SDlab) and the API tolerates either; this project sends4for V5 (the value used by the most recent third-party implementations) and3for older generations, pending live verification.
novelai_image_mcp.nai.models¶
ワイヤーフォーマット用の Pydantic モデル: GenerationRequest、
CharacterPrompt、NovelAIGenerationPlan。
Pure value objects shared by the NovelAI generation pipeline.
- novelai_image_mcp.nai.models.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)¶
Add dunder methods based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.
- class novelai_image_mcp.nai.models.Action(*values)¶
ベースクラス:
StrEnum- GENERATE = 'generate'¶
- IMG2IMG = 'img2img'¶
- INPAINT = 'infill'¶
- class novelai_image_mcp.nai.models.Model(*values)¶
ベースクラス:
StrEnum- V3 = 'nai-diffusion-3'¶
- V3_INPAINT = 'nai-diffusion-3-inpainting'¶
- FURRY = 'nai-diffusion-furry-3'¶
- FURRY_INPAINT = 'nai-diffusion-furry-3-inpainting'¶
- V4 = 'nai-diffusion-4-full'¶
- V4_INPAINT = 'nai-diffusion-4-full-inpainting'¶
- V4_CURATED = 'nai-diffusion-4-curated-preview'¶
- V4_CURATED_INPAINT = 'nai-diffusion-4-curated-inpainting'¶
- V4_5 = 'nai-diffusion-4-5-full'¶
- V4_5_INPAINT = 'nai-diffusion-4-5-full-inpainting'¶
- V4_5_CURATED = 'nai-diffusion-4-5-curated'¶
- V4_5_CURATED_INPAINT = 'nai-diffusion-4-5-curated-inpainting'¶
- V5 = 'nai-diffusion-5-full'¶
- V5_CURATED = 'nai-diffusion-5-curated'¶
- V5_INPAINT = 'nai-diffusion-5-full-inpainting'¶
- class novelai_image_mcp.nai.models.NoiseSchedule(*values)¶
ベースクラス:
StrEnum- NATIVE = 'native'¶
- KARRAS = 'karras'¶
- EXPONENTIAL = 'exponential'¶
- POLYEXPONENTIAL = 'polyexponential'¶
- class novelai_image_mcp.nai.models.Sampler(*values)¶
ベースクラス:
StrEnum- EULER = 'k_euler'¶
- EULER_ANCESTRAL = 'k_euler_ancestral'¶
- DPM_2S_ANCESTRAL = 'k_dpmpp_2s_ancestral'¶
- DPM_2M = 'k_dpmpp_2m'¶
- DPM_2M_SDE = 'k_dpmpp_2m_sde'¶
- DPM_SDE = 'k_dpmpp_sde'¶
- DDIM = 'ddim_v3'¶
- novelai_image_mcp.nai.models.is_v4_model(model)¶
True for structured-prompt (V4+) models: V4 / V4.5 / V5 families.
These use the
/ai/generate-image-streamendpoint (MessagePack) and thev4_prompt/v4_negative_promptcaption payload shape. The name is retained for backward compatibility (publicnaiAPI).
- novelai_image_mcp.nai.models.normalize_tags(values)[ソース]¶
Trim tags and remove case-insensitive duplicates while preserving order.
- novelai_image_mcp.nai.models.normalize_negative_prompt(value)[ソース]¶
Split comma/newline negative prompt text into normalized tags.
- class novelai_image_mcp.nai.models.CharacterIntent(description: 'str', tags: 'tuple[str, ...]', negative_tags: 'tuple[str, ...]', center: 'PositionCoord')[ソース]¶
ベースクラス:
object- パラメータ:
- center: PositionCoord¶
- class novelai_image_mcp.nai.models.GenerationHints(width: 'int | None' = None, height: 'int | None' = None, steps: 'int | None' = None, scale: 'float | None' = None, sampler: 'str | None' = None, seed: 'int | None' = None, negative_tags: 'tuple[str, ...]' = ())[ソース]¶
ベースクラス:
object- パラメータ:
- class novelai_image_mcp.nai.models.PromptIntent(source_language: 'str', english_description: 'str', base_tags: 'tuple[str, ...]', generation: 'GenerationHints', characters: 'tuple[CharacterIntent, ...]', search_required: 'bool', search_query: 'str | None', search_reason: 'str | None')[ソース]¶
ベースクラス:
object- パラメータ:
source_language (str)
english_description (str)
generation (GenerationHints)
characters (tuple[CharacterIntent, ...])
search_required (bool)
search_query (str | None)
search_reason (str | None)
- generation: GenerationHints¶
- characters: tuple[CharacterIntent, ...]¶
- class novelai_image_mcp.nai.models.VisualResearch(facts: 'tuple[str, ...]', sources: 'tuple[str, ...]')[ソース]¶
ベースクラス:
object
- class novelai_image_mcp.nai.models.TipoRequest(description: 'str', tags: 'tuple[str, ...]', visual_facts: 'tuple[str, ...]', seed: 'int')[ソース]¶
ベースクラス:
object
- class novelai_image_mcp.nai.models.TipoPrompt(natural_language: 'str', tags: 'tuple[str, ...]')[ソース]¶
ベースクラス:
object
- class novelai_image_mcp.nai.models.GenerationOverrides(width: 'int | None' = None, height: 'int | None' = None, steps: 'int | None' = None, scale: 'float | None' = None, sampler: 'str | None' = None, seed: 'int | None' = None, negative_prompt: 'str | None' = None)[ソース]¶
ベースクラス:
object- パラメータ:
- class novelai_image_mcp.nai.models.NovelAIGenerationPlan(prompt: 'str', negative_prompt: 'str', width: 'int', height: 'int', steps: 'int', scale: 'float', sampler: 'str', seed: 'int', base_caption: 'str', char_captions: 'tuple[dict[str, object], ...]', character_prompts: 'tuple[dict[str, object], ...]', use_coords: 'bool')[ソース]¶
ベースクラス:
object- パラメータ:
- class novelai_image_mcp.nai.models.CharacterPrompt(prompt: 'str', negative_prompt: 'str' = '', x: 'float' = 0.5, y: 'float' = 0.5, enabled: 'bool' = True)[ソース]¶
ベースクラス:
object
- class novelai_image_mcp.nai.models.GenerationRequest(prompt, base_caption=None, model=Model.V4_5, action=Action.GENERATE, negative_prompt='', width=832, height=1216, n_samples=1, steps=28, scale=5.0, sampler=Sampler.EULER_ANCESTRAL, seed=0, extra_noise_seed=None, noise_schedule=NoiseSchedule.KARRAS, quality=True, uc_preset=0, dynamic_thresholding=False, cfg_rescale=0.0, smea=None, smea_dynamic=None, auto_smea=False, image=None, mask=None, strength=None, noise=None, add_original_image=True, controlnet_strength=1.0, controlnet_condition=None, controlnet_model=None, references=(), reference_information=(), reference_strengths=(), character_prompts=(), use_coords=False, use_order=True, legacy_uc=False, normalize_reference_strengths=True, deliberate_euler_ancestral_bug=False, prefer_brownian=True, skip_cfg_above_sigma=None, legacy=False, legacy_v3_extend=False, inpaint_img2img_strength=None, straight_alpha=False, estimate_only=False)[ソース]¶
ベースクラス:
objectComplete NovelAI generation request independent of the chat planner.
- パラメータ:
prompt (str)
base_caption (str | None)
model (Model)
action (Action)
negative_prompt (str)
width (int)
height (int)
n_samples (int)
steps (int)
scale (float)
seed (int)
extra_noise_seed (int | None)
noise_schedule (NoiseSchedule | str)
quality (bool)
uc_preset (int)
dynamic_thresholding (bool)
cfg_rescale (float)
smea (bool | None)
smea_dynamic (bool | None)
auto_smea (bool)
image (str | None)
mask (str | None)
strength (float | None)
noise (float | None)
add_original_image (bool)
controlnet_strength (float)
controlnet_condition (str | None)
controlnet_model (str | None)
character_prompts (tuple[CharacterPrompt, ...])
use_coords (bool)
use_order (bool)
legacy_uc (bool)
normalize_reference_strengths (bool)
deliberate_euler_ancestral_bug (bool)
prefer_brownian (bool)
skip_cfg_above_sigma (int | None)
legacy (bool)
legacy_v3_extend (bool)
inpaint_img2img_strength (int | None)
straight_alpha (bool)
estimate_only (bool)
- noise_schedule: NoiseSchedule | str¶
- character_prompts: tuple[CharacterPrompt, ...]¶
- estimate_anlas_cost(*, opus=False)[ソース]¶
Estimate provider Anlas cost using the public web-client formula.
Note: on V5, Opus free generations (normal resolution, <=28 steps) are subject to NovelAI's refillable "battery" usage limit; once exhausted the API silently bills Anlas instead of erroring, so the estimate here covers the paid cost regardless of quota state.
novelai_image_mcp.nai.auth¶
Argon2id によるアクセスキー導出 + リクエストごとのトラッキングヘッダー。
NovelAI credential validation and access-key derivation.
- novelai_image_mcp.nai.auth.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)¶
Add dunder methods based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.
- class novelai_image_mcp.nai.auth.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])¶
ベースクラス:
dateThe year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.
- astimezone()¶
tz -> convert to local time in new timezone tz
- classmethod combine()¶
date, time -> datetime with same date and time fields
- ctime()¶
Return ctime() style string.
- date()¶
Return date object with same year, month and day.
- dst()¶
Return self.tzinfo.dst(self).
- fold¶
- classmethod fromisoformat(object, /)¶
string -> datetime from a string in most ISO 8601 formats
- classmethod fromtimestamp()¶
timestamp[, tz] -> tz's local time from POSIX timestamp.
- hour¶
- isoformat()¶
[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to 'T'. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds' and 'microseconds'.
- max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)¶
- microsecond¶
- min = datetime.datetime(1, 1, 1, 0, 0)¶
- minute¶
- classmethod now(tz=None)¶
Returns new datetime object representing current time local to tz.
- tz
Timezone object.
If no tz is specified, uses local timezone.
- replace()¶
Return datetime with new specified fields.
- resolution = datetime.timedelta(microseconds=1)¶
- second¶
- classmethod strptime()¶
string, format -> new datetime parsed from a string (like time.strptime()).
- time()¶
Return time object with same time but with tzinfo=None.
- timestamp()¶
Return POSIX timestamp as float.
- timetuple()¶
Return time tuple, compatible with time.localtime().
- timetz()¶
Return time object with same time and tzinfo.
- tzinfo¶
- tzname()¶
Return self.tzinfo.tzname(self).
- classmethod utcfromtimestamp()¶
Construct a naive UTC datetime from a POSIX timestamp.
- classmethod utcnow()¶
Return a new datetime representing UTC day and time.
- utcoffset()¶
Return self.tzinfo.utcoffset(self).
- utctimetuple()¶
Return UTC time tuple, compatible with time.localtime().
- class novelai_image_mcp.nai.auth.blake2b(data=b'', *, digest_size=64, key=b'', salt=b'', person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True, string=None)¶
ベースクラス:
objectReturn a new BLAKE2b hash object.
- MAX_DIGEST_SIZE = 64¶
- MAX_KEY_SIZE = 64¶
- PERSON_SIZE = 16¶
- SALT_SIZE = 16¶
- block_size¶
- copy()¶
Return a copy of the hash object.
- digest()¶
Return the digest value as a bytes object.
- digest_size¶
- hexdigest()¶
Return the digest value as a string of hexadecimal digits.
- name¶
- update(data, /)¶
Update this hash object's state with the provided bytes-like object.
- class novelai_image_mcp.nai.auth.NovelAICredentials(token: 'str | None' = None, username: 'str | None' = None, password: 'str | None' = None)[ソース]¶
ベースクラス:
object
- novelai_image_mcp.nai.auth.derive_access_key(credentials)[ソース]¶
Derive the 64-character NovelAI login key from username/password.
- パラメータ:
credentials (NovelAICredentials)
- 戻り値の型:
novelai_image_mcp.nai.payload¶
build_generation_payload — ワイヤーフォーマットのエンコーダー(MessagePack 互換)。
NovelAI V4+ / V5 wire payload mapping.
- class novelai_image_mcp.nai.payload.Model(*values)¶
ベースクラス:
StrEnum- V3 = 'nai-diffusion-3'¶
- V3_INPAINT = 'nai-diffusion-3-inpainting'¶
- FURRY = 'nai-diffusion-furry-3'¶
- FURRY_INPAINT = 'nai-diffusion-furry-3-inpainting'¶
- V4 = 'nai-diffusion-4-full'¶
- V4_INPAINT = 'nai-diffusion-4-full-inpainting'¶
- V4_CURATED = 'nai-diffusion-4-curated-preview'¶
- V4_CURATED_INPAINT = 'nai-diffusion-4-curated-inpainting'¶
- V4_5 = 'nai-diffusion-4-5-full'¶
- V4_5_INPAINT = 'nai-diffusion-4-5-full-inpainting'¶
- V4_5_CURATED = 'nai-diffusion-4-5-curated'¶
- V4_5_CURATED_INPAINT = 'nai-diffusion-4-5-curated-inpainting'¶
- V5 = 'nai-diffusion-5-full'¶
- V5_CURATED = 'nai-diffusion-5-curated'¶
- V5_INPAINT = 'nai-diffusion-5-full-inpainting'¶
- novelai_image_mcp.nai.payload.is_v4_model(model)¶
True for structured-prompt (V4+) models: V4 / V4.5 / V5 families.
These use the
/ai/generate-image-streamendpoint (MessagePack) and thev4_prompt/v4_negative_promptcaption payload shape. The name is retained for backward compatibility (publicnaiAPI).
- novelai_image_mcp.nai.payload.is_v5_model(model)¶
True for NovelAI Diffusion V5 models (Full / Curated / Inpainting).
- novelai_image_mcp.nai.payload.params_version_for(model)¶
Return the NovelAI
params_versionfor a model.V5 clients ship both
3(Marinara-Engine) and4(Auto-NovelAI, SDlab) and the API tolerates either; this project sends4for V5 (the value used by the most recent third-party implementations) and3for older generations, pending live verification.
- class novelai_image_mcp.nai.payload.GenerationRequest(prompt, base_caption=None, model=Model.V4_5, action=Action.GENERATE, negative_prompt='', width=832, height=1216, n_samples=1, steps=28, scale=5.0, sampler=Sampler.EULER_ANCESTRAL, seed=0, extra_noise_seed=None, noise_schedule=NoiseSchedule.KARRAS, quality=True, uc_preset=0, dynamic_thresholding=False, cfg_rescale=0.0, smea=None, smea_dynamic=None, auto_smea=False, image=None, mask=None, strength=None, noise=None, add_original_image=True, controlnet_strength=1.0, controlnet_condition=None, controlnet_model=None, references=(), reference_information=(), reference_strengths=(), character_prompts=(), use_coords=False, use_order=True, legacy_uc=False, normalize_reference_strengths=True, deliberate_euler_ancestral_bug=False, prefer_brownian=True, skip_cfg_above_sigma=None, legacy=False, legacy_v3_extend=False, inpaint_img2img_strength=None, straight_alpha=False, estimate_only=False)¶
ベースクラス:
objectComplete NovelAI generation request independent of the chat planner.
- パラメータ:
prompt (str)
base_caption (str | None)
model (Model)
action (Action)
negative_prompt (str)
width (int)
height (int)
n_samples (int)
steps (int)
scale (float)
seed (int)
extra_noise_seed (int | None)
noise_schedule (NoiseSchedule | str)
quality (bool)
uc_preset (int)
dynamic_thresholding (bool)
cfg_rescale (float)
smea (bool | None)
smea_dynamic (bool | None)
auto_smea (bool)
image (str | None)
mask (str | None)
strength (float | None)
noise (float | None)
add_original_image (bool)
controlnet_strength (float)
controlnet_condition (str | None)
controlnet_model (str | None)
character_prompts (tuple[CharacterPrompt, ...])
use_coords (bool)
use_order (bool)
legacy_uc (bool)
normalize_reference_strengths (bool)
deliberate_euler_ancestral_bug (bool)
prefer_brownian (bool)
skip_cfg_above_sigma (int | None)
legacy (bool)
legacy_v3_extend (bool)
inpaint_img2img_strength (int | None)
straight_alpha (bool)
estimate_only (bool)
- noise_schedule: NoiseSchedule | str¶
- character_prompts: tuple[CharacterPrompt, ...]¶
- estimate_anlas_cost(*, opus=False)¶
Estimate provider Anlas cost using the public web-client formula.
Note: on V5, Opus free generations (normal resolution, <=28 steps) are subject to NovelAI's refillable "battery" usage limit; once exhausted the API silently bills Anlas instead of erroring, so the estimate here covers the paid cost regardless of quota state.
- class novelai_image_mcp.nai.payload.NovelAIGenerationPlan(prompt: 'str', negative_prompt: 'str', width: 'int', height: 'int', steps: 'int', scale: 'float', sampler: 'str', seed: 'int', base_caption: 'str', char_captions: 'tuple[dict[str, object], ...]', character_prompts: 'tuple[dict[str, object], ...]', use_coords: 'bool')¶
ベースクラス:
object- パラメータ:
- novelai_image_mcp.nai.payload.build_payload(plan, *, model)[ソース]¶
Map an already-resolved plan to NovelAI's V4.5/V5 request shape.
- パラメータ:
plan (NovelAIGenerationPlan)
model (str)
- 戻り値の型:
novelai_image_mcp.nai.response¶
レスポンスのパース: NovelAIImage、parse_messagepack_images、
parse_zip_images、check_status、GenerationEvent。
NovelAI HTTP, ZIP, and MessagePack response parsing.
- novelai_image_mcp.nai.response.dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)¶
Add dunder methods based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method is added. If frozen is true, fields may not be assigned to after instance creation. If match_args is true, the __match_args__ tuple is added. If kw_only is true, then by default all fields are keyword-only. If slots is true, a new class with a __slots__ attribute is returned.
- class novelai_image_mcp.nai.response.Any(*args, **kwargs)¶
ベースクラス:
objectSpecial type indicating an unconstrained type.
Any is assignable to every type.
Any assumed to have all methods and attributes.
All values are assignable to Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any cannot be used with instance checks.
- novelai_image_mcp.nai.response.cast(typ, val)¶
Cast a value to a type.
This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible).
- novelai_image_mcp.nai.response.explain(code)¶
Return NovelAI's official explanation for a documented error code.
Undocumented codes (including API-supplied MessagePack stream codes) return
None— the API's own message is then the best explanation.
- novelai_image_mcp.nai.response.parse_error_body(content)¶
Extract
(code, message)from a NovelAI error body.NovelAI returns JSON in several shapes —
{"statusCode", "message"},{"code", "message"},{"error": ...}, or a bare{"message"}— or, on some legacy paths, raw text. Falls back to the decoded text when neither a code nor a message field is present.
- class novelai_image_mcp.nai.response.NovelAIImage(filename: 'str', data: 'bytes')[ソース]¶
ベースクラス:
object
- class novelai_image_mcp.nai.response.GenerationEvent(event_type: 'str', sample_index: 'int', step_index: 'int', generation_id: 'str', sigma: 'float', image: 'NovelAIImage')[ソース]¶
ベースクラス:
object- パラメータ:
- image: NovelAIImage¶
- novelai_image_mcp.nai.response.check_status(status_code, content)[ソース]¶
Raise the domain error associated with an HTTP status.
The NovelAI error code (body
statusCode/code, or the HTTP status when the body carries none) and its official explanation are attached to the raised exception and appended to its message.
- novelai_image_mcp.nai.response.parse_zip_images(content)[ソース]¶
- パラメータ:
content (bytes)
- 戻り値の型:
tuple[NovelAIImage, ...]
- class novelai_image_mcp.nai.response.MessagePackStreamParser[ソース]¶
ベースクラス:
objectIncrementally parse NovelAI's big-endian length-prefixed MessagePack.
- feed(chunk)[ソース]¶
- パラメータ:
chunk (bytes)
- 戻り値の型:
tuple[GenerationEvent, ...]
- novelai_image_mcp.nai.response.parse_messagepack_events(content)[ソース]¶
- パラメータ:
content (bytes)
- 戻り値の型:
tuple[GenerationEvent, ...]
- novelai_image_mcp.nai.response.parse_messagepack_images(content)[ソース]¶
- パラメータ:
content (bytes)
- 戻り値の型:
tuple[NovelAIImage, ...]
注釈
上に挙げた例外クラスは check_status で送出するために response へインポートされている
だけです。ドキュメントは定義元のモジュール novelai_image_mcp.nai.exceptions(次の節)にあります。
novelai_image_mcp.nai.exceptions¶
ドメイン例外の階層:
Typed NovelAI domain failures.
Every exception optionally carries the NovelAI error code (HTTP status or
API-supplied stream code) and, when documented, NovelAI's official
explanation — see nai.errors. The code and explanation are appended to
the message (so they reach MCP tool callers and the CLI) and exposed as
attributes for programmatic handling.
- exception novelai_image_mcp.nai.exceptions.NovelAIError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
ExceptionBase class for NovelAI failures.
codeis the NovelAI error code when known (Nonefor transport, timeout, or local validation failures that carry no server code);explanationis NovelAI's official explanation for documented codes.
- exception novelai_image_mcp.nai.exceptions.NovelAIProviderError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIErrorNovelAI rejected or failed the request.
- exception novelai_image_mcp.nai.exceptions.NovelAIValidationError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIProviderErrorThe request is invalid.
- exception novelai_image_mcp.nai.exceptions.NovelAIAuthenticationError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIProviderErrorCredentials are missing, invalid, or expired.
- exception novelai_image_mcp.nai.exceptions.NovelAIInsufficientCreditsError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIProviderErrorThe account has insufficient Anlas or no subscription.
- exception novelai_image_mcp.nai.exceptions.NovelAIConcurrencyError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIProviderErrorThe account hit a concurrency or rate limit.
- exception novelai_image_mcp.nai.exceptions.NovelAITimeoutError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIErrorA request exceeded its timeout.
- exception novelai_image_mcp.nai.exceptions.NovelAITransportError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIErrorThe request could not reach NovelAI.
- exception novelai_image_mcp.nai.exceptions.NovelAIResponseError(message, *, code=None, explanation=None)[ソース]¶
ベースクラス:
NovelAIErrorNovelAI returned malformed or unsupported data.
novelai_image_mcp.nai.errors¶
エラーボディのパースと公式エラーコードの説明: ErrorInfo、
OFFICIAL_CODE_EXPLANATIONS、explain、parse_error_body。
NovelAI error-body parsing and official error-code explanations.
Every error raised toward NovelAI's API carries the error code and —
where documented — NovelAI's official explanation text (see
OFFICIAL_CODE_EXPLANATIONS). Codes sent inside MessagePack stream errors by
the API itself ({code, message} events) are passed through verbatim.
- novelai_image_mcp.nai.errors.OFFICIAL_CODE_EXPLANATIONS: dict[int, str] = {400: 'invalid request (validation failed)', 401: 'authentication failed (missing, invalid, or expired credentials)', 402: 'active subscription or Anlas required', 409: 'request conflicted with server state', 429: 'rate limit or concurrency limit reached'}¶
Official error codes documented by NovelAI's API docs (https://api.novelai.net/docs) and the official FAQ. 5xx are deliberately folded into the generic provider-error bucket rather than enumerated.
- class novelai_image_mcp.nai.errors.ErrorInfo(code, message, raw)[ソース]¶
ベースクラス:
objectNormalized error payload extracted from a NovelAI error body.
- novelai_image_mcp.nai.errors.explain(code)[ソース]¶
Return NovelAI's official explanation for a documented error code.
Undocumented codes (including API-supplied MessagePack stream codes) return
None— the API's own message is then the best explanation.
- novelai_image_mcp.nai.errors.parse_error_body(content)[ソース]¶
Extract
(code, message)from a NovelAI error body.NovelAI returns JSON in several shapes —
{"statusCode", "message"},{"code", "message"},{"error": ...}, or a bare{"message"}— or, on some legacy paths, raw text. Falls back to the decoded text when neither a code nor a message field is present.
novelai_image_mcp.nai.service¶
create_novelai_client ファクトリー + NovelAIConfigLike プロトコル。ファクトリーは
設定ライクなオブジェクトと httpx.AsyncClient を受け取り、完全に配線済みの
NovelAIClient を返します。
High-level NovelAI service construction for the MCP server and CLI consumers.
A duck-typed config object (NovelAIConfigLike Protocol) keeps the nai
package decoupled from the MCP wrapper. The wrapper's NovelAISettings
(pydantic-settings, env-driven) satisfies this protocol structurally; see
novelai_image_mcp.settings.
- class novelai_image_mcp.nai.service.NovelAIConfigLike(*args, **kwargs)[ソース]¶
ベースクラス:
ProtocolStructural shape of any object supplying NovelAI client configuration.
- novelai_image_mcp.nai.service.create_novelai_client(config, *, http_client=None)[ソース]¶
Create a complete client from a configuration object.
Accepts either a token or a complete username/password pair. Pass a shared
http_clientwhen the caller (e.g. the MCP lifespan) wants connection pooling across requests; otherwise the client owns a private session.- パラメータ:
config (NovelAIConfigLike)
http_client (httpx.AsyncClient | None)
- 戻り値の型:
公式エラーコード¶
このクライアントが送出するすべての NovelAI エラーは、エラー code(HTTP ステータス、または
API 自身のストリームコード)と、文書化されている場合は NovelAI の公式説明を保持します。どちらも
メッセージに追記され、例外の属性として公開されます:
コード |
意味(公式) |
|---|---|
|
リクエストが不正(バリデーション失敗) |
|
認証に失敗 |
|
有効なサブスクリプションまたは Anlas が必要 |
|
リクエストの競合 |
|
レート制限 / 同時実行数の上限 |
|
NovelAI 上流のエラー |
すべての例外は NovelAIError を継承し、.code /
.explanation を公開します(サーバーコードを持たないトランスポート、タイムアウト、
ローカルバリデーションの失敗では両方とも None)。パース用ヘルパーは
novelai_image_mcp.nai.errors モジュールを参照してください。