Skip to content

Documentation navigation

API Overview

Top-level SDK API map and import surface.

#SDK Reference

The supported public SDK surface, grouped by import path and linked to the detailed reference pages.

This page is the hub. If you are building your first agent, start with the Getting Started guide and the Agent reference. Come back here when you need to find an exact name or see how the pieces fit together. This page documents the behavioral surface (how to build an agent and stream from it). For the shapes that behavior produces and consumes (InvokeResponse, its token_usage dictionary, and privacy and billing models), see Shared Data Models.

#What this is

maivn is a Python SDK for building agentic systems. You describe what your agent can do (its tools, its dependencies, its configuration) as plain Python objects, and the SDK runs each request through an orchestrator that decides what to call and when. Everything you need lives behind a single import:

Python
from maivn import Agent
from maivn.messages import HumanMessage

agent = Agent(name='assistant', api_key='your-api-key')
response = agent.invoke([HumanMessage(content='Hello!')])
print(response.response)

The whole programming surface is the SDK. You construct Agent and Swarm objects, register tools with decorators, tune behavior with typed config models, and read results off an InvokeResponse. Tool code runs locally in your environment and is never sent: for each tool the SDK sends its name, description and parameter types for planning. The data a run needs (your messages and files, and tool-call arguments and results) does go to the platform and to the model provider that serves the run. Values you mark as private are replaced with placeholders before a model sees them.

Note invoke() returns an InvokeResponse. Use response.response for the final assistant text and response.result for structured or final-tool output.

#The public import surface

Everything below is exported from maivn, 202 names in all. They match maivn.__all__. Event normalization and frontend-bridge APIs live in maivn.events, message types live in maivn.messages, and file helpers live in maivn.files and maivn.artifact_images.

Python
from maivn import (
    # Version
    __version__,

    # Core classes
    Agent,
    Swarm,
    Client,
    ClientBuilder,
    ClientConfig,
    BaseScope,
    RunOptions,
    InvokeResponse,
    StreamEvent,

    # MCP
    MCPServer,
    MCPAutoSetup,

    # Decorators
    tool_output,
    toolify,
    toolset,
    toolify_options,
    toolset_options,
    compose_argument_policy,
    depends_on_tool,
    depends_on_agent,
    depends_on_private_data,
    depends_on_interrupt,
    depends_on_await_for,
    depends_on_reevaluate,
    depends_on_decision,
    requires_producer_reference,

    # Permissions
    PERMISSION_FLAG_NAMES,
    PermissionFlag,
    PermissionSet,
    require_permissions,

    # Provider metadata
    AuthMode,
    ProviderCapability,
    ProviderMetadata,

    # SDK configuration
    ConfigurationBuilder,
    MaivnConfiguration,
    get_configuration,

    # Session config models
    MemoryConfig,
    MemoryGraphExtractionConfig,
    MemoryInsightExtractionConfig,
    MemoryLevel,
    MemoryPersistenceMode,
    MemoryRetrievalConfig,
    MemorySharingScope,
    MemorySkillExtractionConfig,
    SystemToolsConfig,

    # Model selection
    ModelChoice,
    ModelConfig,
    ModelConfigPart,
    ModelTier,
    PlanningChoice,
    PlanningTier,

    # Memory resources
    MemoryDeleteResponse,
    MemoryEnrichmentReceipt,
    MemoryInsight,
    MemoryInsightCreate,
    MemoryInsightOrigin,
    MemoryInsightType,
    MemoryInsightUpdate,
    MemoryPersistenceCeiling,
    MemoryResource,
    MemoryResourceBindingType,
    MemoryResourceDetail,
    MemoryResourceStatus,
    MemoryScope,
    MemoryScopeRequest,
    MemorySkill,
    MemorySkillCreate,
    MemorySkillOrigin,
    MemorySkillStatus,
    MemorySkillStep,
    MemorySkillUpdate,
    MemoryUnboundResourceCandidate,
    OrganizationMemoryPolicy,
    OrganizationMemoryPurgeResult,
    ProjectMemoryResources,

    # Resources and skills
    ResourceDeleteResponse,
    ResourcePatch,
    ResourceRecord,
    ResourceScopeRequest,
    ResourceUploadOptions,
    Skill,
    SkillScopeRequest,
    SkillSet,
    SkillStep,
    parse_skill_markdown,

    # PII and private data
    CoverRegion,
    HIPAA_SAFE_HARBOR_CATEGORIES,
    PIIWhitelist,
    PIIWhitelistEntry,
    PrivateData,
    RedactedMessage,
    RedactionPreviewRequest,
    RedactionPreviewResponse,
    EncryptedFilePrivateDataStore,
    InMemoryPrivateDataStore,
    LocalVaultConfig,
    PrivateDataStore,

    # Billing and usage
    BillingCurrentUsage,
    BillingPlan,
    BillingUsage,
    BillingUsageApiKey,
    BillingUsageBreakdown,
    BillingUsageProject,
    BillingUsageTotals,
    ProviderModelUsage,
    ProviderUsage,
    TokenCategoryUsage,
    TokenUsageByCategory,
    TokenUsageCategory,

    # Threads
    ApprovalDecision,
    BoundThread,
    ThreadAccepted,
    ThreadCheckpoint,
    ThreadState,

    # Artifacts
    ArtifactDownload,
    ArtifactListPage,
    ArtifactMetadata,
    ArtifactPreview,
    ArtifactRef,
    OrdinaryArtifactRef,
    PrivateArtifactRef,
    PrivateArtifactsClient,
    TransientVaultClientProof,

    # Hosted jobs
    HostedJobOptions,
    HostedJobStatus,

    # Exceptions
    AsyncContextError,
    ConfigurationError,
    DurableBoundaryRefusedError,
    MaivnHTTPError,
    MaivnSDKError,
    PlanLimitExceededError,
    ResourceRegistrationError,
    VaultSetupError,
    PrivateArtifactError,
    PrivateArtifactAuthorizationDeniedError,
    PrivateArtifactEffectFailedError,
    PrivateArtifactGrantExpiredError,
    PrivateArtifactTimeoutError,
    SkillMarkdownError,
    SkillChildNotFoundError,
    SkillCycleError,
    SkillFrontmatterError,

    # Logging
    configure_logging,
    get_logger,

    # Scheduling
    AtSchedule,
    CronInvocationBuilder,
    CronSchedule,
    IntervalSchedule,
    JitterDistribution,
    JitterSpec,
    MisfirePolicy,
    OverlapPolicy,
    Retry,
    RetryBackoff,
    RunRecord,
    RunStatus,
    Schedule,
    ScheduledJob,
    list_jobs,
    stop_all_jobs,

    # Durable triggers
    Trigger,
    TriggerFireReceipt,
    TriggerInvocationBuilder,
    TriggerOptions,
    TriggerSource,
    RetryPolicy,
    stable_trigger_ids,
    ChainedEventSource,
    EmailToInvokeSource,
    ExternalConnectionEventSource,
    FireTriggerToolSource,
    ManualSource,
    MemoryEventSource,
    ReplyConversationSource,
    ScheduleSource,
    SLATimerSource,
    StorageEventSource,
    WebhookSource,

    # Serving
    ServingEvent,
    ServingListener,
    ServingSession,

    # Interrupts and terminal reporting
    AgentGenerated,
    BackpressurePolicy,
    FollowupInputHandler,
    FollowupOption,
    FollowupQuestion,
    FollowupQuestionsConfig,
    default_terminal_followup,
    default_terminal_interrupt,
)

Event, message and file APIs live in dedicated public submodules:

Python
from maivn.events import AppEvent, EventBridge, RawSSEEvent, normalize_stream
Python
from maivn.messages import HumanMessage, AIMessage, SystemMessage, RedactedMessage
Python
from maivn.files import GeneratedFile, GeneratedFiles, editable_source_archive, generated_file
from maivn.artifact_images import ArtifactImageUnavailableError, ResolvedArtifactImage, resolve_artifact_image

Metadata-only run telemetry lives in its own versioned submodule:

Python
from maivn.telemetry import RunTelemetryEvent, register_listener
from maivn.telemetry.opentelemetry import OpenTelemetryAdapter
Tip You rarely import all of this at once. Most applications need only Agent (or Swarm), one or two decorators, and the message types. Everything else is opt-in.

#Core classes

The objects you instantiate and call. Agent and Swarm are the two entry points. They share tool registration, events(), batch / abatch, thread methods and scheduling. BaseScope supplies the scheduling and trigger helpers. The .structured_output(Model) builder, MCP registration and session_usage() are Agent-only. Swarms use final tools for typed output.

ClassDescriptionReference
AgentPrimary entry point. Holds its tools and credentials, and routes invocations through the orchestrator. Resolves credentials from arguments, selected files, or the process environment. Exposes invoke / stream / ainvoke / astream.Core
SwarmMulti-agent orchestration container. Members carry their own tools. Parent tools can be explicit dependencies. Member list order does not select an entry agent. Adds add_agent / list_agents and the .member dependency-aware registration builder.Core
BaseScopeBase class shared by Agent and Swarm. Supplies scheduling (cron / interval / at), the durable trigger helpers (on_webhook, on_email and the other on_* methods, declared_triggers) and close(). Rarely used directly.Core
ClientConnection manager that carries credentials and connects an Agent or Swarm to the mAIvn service. Usually created for you from an api_key.Core
ClientBuilderFactory for constructing Client instances with explicit settings.Core
RunOptionsPer-call options for invoke, stream and the thread methods.Core
ClientConfigThe frozen configuration a Client uses.Configuration
EventsPublic event models, payload builders, and stream-normalization helpers for surfacing execution state to your backend and frontend.Core
Run TelemetryStable metadata-only run hooks and the optional OpenTelemetry adapter.Observability
MCPServerConfiguration for connecting an external MCP server (stdio or HTTP transport) as a tool provider. MCP tools run locally in your environment.MCP
MCPAutoSetupAuto-setup helper for uvx-based MCP servers.MCP

#How an agent runs

When you call invoke() or stream(), the SDK compiles your tools and config into a request and hands it to the orchestrator. The orchestrator plans which tools to call (it receives each tool's name, description and parameter types, never your code), executes them locally in your process, and synthesizes a response. Your messages and files and the arguments and results of tool calls go to the platform and to the model provider that serves the run, and values you mark as private are replaced with placeholders before a model sees them; see the Private Data Guide. You read the result from InvokeResponse, or consume incremental StreamEvent values.

The async methods (ainvoke / astream) mirror the synchronous ones for native asyncio code, and batch / abatch run independent requests concurrently while preserving input order.

#Decorators

Decorators define tools and declare how a tool relates to other tools, agents, secret data, and the user. @toolify turns a function or Pydantic model into a tool. @toolset marks a class whose methods become tools. Dependency decorators are applied beneath @agent.toolify(...) (or beneath @swarm.member), or chained off the builder returned by toolify(...). See the Dependencies guide for the full data-flow model.

DecoratorDescriptionReference
@toolifyRegister a function or Pydantic model as a tool.Decorators
@toolsetMark a class whose @toolify-marked methods register as a group of tools.Decorators
@depends_on_toolInject another tool's output as an argument.Decorators
@depends_on_agentInject another agent's output as an argument. Both agents must be members of the same Swarm.Decorators
@depends_on_private_dataInject a declared private value at execution time. The model plans against the schema and never sees the raw value.Decorators
@depends_on_interruptPause to collect user input mid-execution.Decorators
@depends_on_await_forHolds a tool until another tool has completed in the same run. Enforced since maivn 2.5.0.Decorators
@depends_on_reevaluateTrigger orchestrator reevaluation after the tool runs, so the plan can adapt.Decorators
@requires_producer_referenceDeclare that a tool argument requires a reference produced by a named upstream tool.Decorators

Artifact production uses generator toolsets from maivn-tools. These tools run in the user's tool environment and return GeneratedFile values through the normal artifact intake. Stored Office files (DOCX, XLSX, PPTX) are downloadable but have no inline preview. PDF and image files (PNG, JPEG) do. See Artifacts.

Python
from maivn import depends_on_tool

@agent.toolify(description='Fetch raw sensor data')
def fetch_sensor_data(sensor_id: str) -> dict:
    return {'sensor_id': sensor_id, 'readings': [72, 73, 71]}

@agent.toolify(description='Analyze sensor readings')
@depends_on_tool(fetch_sensor_data, arg_name='sensor_data')
def analyze_readings(sensor_data: dict) -> dict:
    readings = sensor_data['readings']
    return {'average': sum(readings) / len(readings)}

#Configuration

Two kinds of configuration exist. SDK configuration describes the environment (credentials, timeouts, defaults) and is usually built once from the environment. Session config models are typed objects that carry per-scope or per-call runtime controls. Pass them to Agent(...) / Swarm(...) as defaults, or to invoke() / stream() as overrides.

#SDK configuration

ItemDescriptionReference
MaivnConfigurationTop-level SDK environment/configuration model.Configuration
ConfigurationBuilderBuild SDK configuration from environment variables.Configuration
get_configuration()Return the current SDK configuration.Configuration

#Session config models

ItemDescriptionReference
MemoryConfigMemory retrieval and persistence controls.Session Config
SystemToolsConfigAllowlists and approvals for built-in system tools (web_search, repl, think).Session Config
ModelConfig, ModelChoice, PlanningChoiceScoped model selection for each configurable part of a run (response, thinking, argument composition, REPL, planning).Session Config
ModelTier, PlanningTier, ModelConfigPartLiteral aliases for the tier names and the configurable parts.Session Config

Memory has a dedicated family of resource and policy models (MemoryInsight, MemoryResource, MemorySkill, OrganizationMemoryPolicy, and related enums). See the Memory and Recall guide for how they fit together.

#Privacy and private data

These models declare and govern sensitive values so the SDK can keep them out of model-visible context. The model plans against a schema of key names and types. Real values are injected at tool-execution time, and tool results are scanned and redacted before returning to the model. See the Private Data guide.

Redaction aids, not compliance. phi_mode and HIPAA_SAFE_HARBOR_CATEGORIES are redaction aids. Using them does not make a deployment compliant with health-privacy law, and the hosted Service does not accept protected health information without a separate signed agreement; see the Acceptable Use Policy. mAIvn holds no SOC 2, HIPAA, ISO 27001, or FedRAMP certification, and cannot guarantee that every private value is detected. These controls do not replace required audits and organizational safeguards.

ItemDescriptionReference
PrivateDataDeclares a known private value with optional metadata: key name, label, type, format hint.Private Data guide
RedactedMessageA user message whose sensitive spans are detected and substituted with placeholders.Private Data guide
PIIWhitelist, PIIWhitelistEntryMark specific values, patterns, or entity types as safe to pass through, with required justification. phi_mode refuses entity-type entries for HIPAA Safe Harbor categories.Private Data guide
HIPAA_SAFE_HARBOR_CATEGORIESExported constant: the HIPAA Safe Harbor identifier categories.Private Data guide
RedactionPreviewRequest, RedactionPreviewResponseRequest and response models for Client.preview_redaction().Private Data guide
CoverRegionAn unconditional cover on a page region of an attachment.Private Data guide
PrivateDataStore, InMemoryPrivateDataStore, EncryptedFilePrivateDataStore, LocalVaultConfigWhere caller-declared private values rest between calls.Client

#Threads

A thread is a durable conversation. client.thread(), agent.thread() and swarm.thread() return a BoundThread, whose time_travel(checkpoint_id, message, ...) rewinds the thread and waits for the new path's InvokeResponse. The explicit methods on Client (start_thread, post_thread_message, get_thread, thread_events, time_travel_thread, submit_approval) return or consume ThreadAccepted, ThreadState, ThreadCheckpoint and ApprovalDecision. See Client.

#Artifacts

Files that tools generate come back as ArtifactRef values on response.artifacts. client.artifacts retrieves ordinary files and client.private_artifacts retrieves private ones. See Artifacts for the reference models, both clients, maivn.files and maivn.artifact_images.

#Errors

MaivnSDKError is the base of the SDK's exceptions. MaivnHTTPError and PlanLimitExceededError carry the API error envelope, DurableBoundaryRefusedError reports a privacy-boundary refusal, and private artifact calls raise PrivateArtifactError and its subclasses. See Errors and exceptions.

#Messages

Import message types from maivn.messages. These are the inputs you pass to invoke() / stream() and the assistant turns the SDK returns.

ClassDescriptionReference
HumanMessageUser input message.Messages
AIMessageAssistant response message.Messages
SystemMessageSystem prompt message.Messages
RedactedMessageRequests runtime redaction before model processing.Messages

#Logging

FunctionDescriptionReference
configure_logging()Initialize SDK logging (optionally to a file).Logging
get_logger()Return the SDK logger instance.Logging

#Events

The events surface lets you stream execution state (tool calls, phase indicators, the final response) into your own backend and frontend. The canonical normalize_stream() helper converts a raw stream into a stable, versioned AppEvent contract, payload builders construct individual event payloads, and EventBridge mounts an SSE endpoint. See the Events reference and the Frontend Events guide for the browser client example.

ItemDescriptionReference
AppEvent, UIEvent, RawSSEEventPublic event models for normalized, UI, and raw stream events.Events
APP_EVENT_CONTRACT_VERSIONVersion constant for the AppEvent contract.Events
normalize_stream, normalize_stream_eventConvert raw stream events into the canonical AppEvent shape.Events
build_*_payloadBuilders for individual event payloads (enrichment, final, tool, status message, interrupt, session start, and more).Events
EventBridge, BridgeRegistry, BridgeAudienceMount and manage an SSE bridge with an audience scope.Events
EventBridgeSecurityPolicy, BackpressurePolicyTrust-boundary and backpressure controls for the bridge.Events
forward_normalized_event, forward_normalized_streamForward normalized events/streams to a downstream consumer.Events
NormalizedStreamState, NormalizedEventForwardingStateState objects for normalization and forwarding.Events

Task-list updates reach an events(on_event=...) callback as a dict with category == 'task_list_updated' and the items in event['payload']['items'], but reach normalized consumers as an AppEvent with event_name == 'task_list_updated' and the items in event.task_list.items. The two shapes differ; see Task-list events.

Note Enrichment events are fixed-label phase indicators (for example, "Evaluating request", "Planning actions", "Synthesizing response") streamed between tool calls so consumers can show what the system is doing. Status messages are a separate event family that may appear on the same stream.

#Decisions

The prepared maivn.decisions feature set provides categorical requests, locally authorized platform calls, fallback diagnostics, native batching, before/after invocation plans, typed arguments, function/local-tool dependencies and optional matching. Use the ordinary mAIvn key and platform address. No provider credential or model selector is exposed. See the Decisions API, guide and examples.

#Run telemetry

maivn.telemetry publishes the customer-visible run lifecycle as a closed, versioned metadata schema. The optional maivn[otel] adapter maps runs to traces and tool calls to spans without exporting messages, prompts, arguments, results, or resolved private values. See Run Telemetry.

#Scheduling

Any Agent or Swarm can run on a schedule. cron(...), interval(...), and at(...) return a chainable builder. A remote terminal call returns a durable Trigger. An explicit mode="local" call returns a process-owned ScheduledJob. See the Scheduling reference and the Scheduled Invocation guide.

ItemDescriptionReference
scope.cron(...) / interval(...) / at(...)Build a durable remote trigger or explicitly local scheduled invocation.Scheduling
CronInvocationBuilderChainable builder over invoke / stream / batch and async variants.Scheduling
ScheduledJobLifecycle handle returned by terminal builder calls (on_fire, on_error, stop).Scheduling
JitterSpec, JitterDistributionBounded randomness around fire times.Scheduling
Retry, RetryBackoffRetry policy with constant / linear / exponential backoff.Scheduling
Schedule, CronSchedule, IntervalSchedule, AtScheduleSchedule descriptor models.Scheduling
MisfirePolicy, OverlapPolicyPolicies for missed and overlapping fires.Scheduling
RunRecord, RunStatusOutcome of a single fire.Scheduling
list_jobs() / stop_all_jobs()Process-wide registry helpers.Scheduling

#Other exports

These exports have guides but no dedicated reference page. Their signatures are in the SDK source.

ItemsWhat they areWhere to read
Skill, SkillSet, SkillStep, SkillScopeRequest, parse_skill_markdownFirst-class skill records, and the parser for skill markdown files.SDK Resource Configuration
ResourceRecord, ResourcePatch, ResourceScopeRequest, ResourceUploadOptions, ResourceDeleteResponseResource records and the request models for client.resources.SDK Resource Configuration
MemoryInsightCreate, MemoryInsightUpdate, MemorySkillCreate, MemorySkillUpdate, MemorySkillStep, MemoryScope, MemoryScopeRequest, MemoryDeleteResponse, MemoryEnrichmentReceiptRequest and response models for client.memory.Memory and Recall guide
HostedJobOptions, HostedJobStatusOpt-in bounds for a hosted job, and its durable status.Hosted jobs guide
Trigger, TriggerInvocationBuilder, TriggerFireReceipt, TriggerOptions, TriggerSource, RetryPolicy, stable_trigger_ids, and the *Source models (WebhookSource, ScheduleSource, ManualSource, EmailToInvokeSource and others)Durable triggers attached to an Agent or Swarm.Scheduling and the trigger guides, such as Email triggers
ServingSession, ServingEvent, ServingListenerA local process announced to the platform for one agent version, and the events it emits.Scheduled Invocation guide

#Token usage and billing

Responses expose runtime-reported token usage as an extensible dictionary, and Agent.session_usage() and Client.session_usage() return provider-reported counts as ProviderUsage. The public billing models validate aggregated plan and quota payloads, but the current public Client does not fetch those payloads. See the Billing reference and the Billing and Usage guide.

#Quick navigation by goal

#Next steps

#Version

Python
from maivn import __version__
print(__version__)