Skip to content

Documentation navigation

Troubleshooting

Common failure modes and practical resolution steps.

#Troubleshooting

Common errors and solutions when using the mAIvn SDK. This is the cookbook: a specific error message, its cause, and a copy-pasteable fix. For the exception types behind these messages, including the public MaivnSDKError hierarchy, validation failures and layered try/except handling, see Errors & Exceptions.

#Common Errors

#Agent requires either a Client instance or an api_key

Error:

Plain text
ValueError: Agent requires either a Client instance or an api_key, or MAIVN_API_KEY in the process environment.

Cause: The agent could not resolve credentials from its arguments, a selected credential file, or the process environment. Client() raises ConfigurationError for the same condition. See Authentication for the lookup order.

Solution:

Python
# Option 1: Provide api_key
agent = Agent(name='my_agent', api_key='your-api-key')

# Option 2: Use environment variable
# Set MAIVN_API_KEY in your environment
agent = Agent(name='my_agent')

# Option 3: Provide a Client
client = Client(api_key='your-api-key')
agent = Agent(name='my_agent', client=client)

#Targeted tool selection fails

targeted_tools must contain at least one registered tool name. An empty list raises ValueError: targeted_tools must contain at least one tool name. Unknown names raise ValueError: Unknown targeted tool(s): ... followed by the available tools. The SDK includes the selected tools' declared tool dependencies automatically.

targeted_tools can be combined with structured_output=Model in v2: selection happens first, then the SDK adds or promotes the final model constructor. It can also be combined with force_final_tool=True; include the intended final tool in the selected set.

#Multiple tools marked with final_tool=True

An agent can register multiple final tools in v2. The local tool validator rejects duplicate tool names, not multiple final-tool flags. If an older example tells you to remove all but one final tool, that restriction does not apply to this SDK.

Swarm validation has a separate ownership rule: when multiple member agents own final tools, designate one member with use_as_final_output=True. See the Swarm reference.

#Argument not found in function signature

Dependency decorators do not consistently validate parameter names when they are applied. A mismatch can surface later during schema compilation or execution. Check that arg_name matches the function parameter or Pydantic field exactly.

Solution: Use the correct parameter name:

Python
# Wrong: arg_name doesn't match
@depends_on_tool(other_tool, arg_name='data')
def my_tool(result: dict) -> dict: ...

# Correct: arg_name matches parameter
@depends_on_tool(other_tool, arg_name='result')
def my_tool(result: dict) -> dict: ...

#force_final_tool requires at least one tool with final_tool=True

Error:

Plain text
ValueError: force_final_tool=True requires at least one tool with final_tool=True.
Agent 'my_agent' has 3 tool(s) but none are final.

Cause: You used force_final_tool=True but no tool is marked as final. The check is skipped when the same call passes structured_output=Model.

Solution: Mark one tool as final:

Python
@agent.toolify(final_tool=True)  # Add final_tool=True
class FinalOutput(BaseModel):
    result: str

# Or register the final model imperatively.
agent.add_tool(FinalOutput, final_tool=True)

If you use constructor-based tools, raw functions and models are registered with default tool options. Use agent.add_tool(..., final_tool=True) when a Pydantic model must be the agent's final tool.

#Connection errors

Error:

Plain text
httpx.ConnectError: [Errno 111] Connection refused

Cause: The SDK cannot connect to the mAIvn API.

Solutions:

  1. Check the address: base_url=, MAIVN_BASE_URL, or the default https://api.maivn.io.
  2. For a local stack, check that it is running and that MAIVN_BASE_URL points at its single address.
  3. Check network connectivity and firewall rules.

#Timeout errors

Error:

Plain text
httpx.ReadTimeout: timed out

Cause: The HTTP read exceeded its configured timeout while waiting for data.

Solutions:

Python
# Increase the HTTP timeout (default 30 seconds)
client = Client(
    api_key='...',
    timeout_seconds=120,
)

Client has no http_timeout argument. timeout is accepted as an alias of timeout_seconds.

tool_execution_timeout ends a tool that runs longer than its limit (default 600 seconds); see Tool timeout. It does not set a limit on the whole run: for that, use a hosted job and its max_duration_seconds. An HTTP timeout does not cancel a server invocation. See Reliability.

#MCP server startup failure

Error:

Plain text
ValueError: stdio MCPServer requires command or auto_setup

Cause: MCP server configuration is incomplete. The MCPServer constructor accepts it, and the error appears when the SDK starts the server.

Solution:

Python
# Provide command
MCPServer(
    name='my_server',
    transport='stdio',
    command='my-mcp-server',  # Add this
)

# Or use auto_setup
MCPServer(
    name='my_server',
    transport='stdio',
    auto_setup=MCPAutoSetup(package='my-mcp-package'),
)

A stdio server that starts and then dies fails with MCP stdio server 'my_server' closed unexpectedly (exit code 1), naming the server and its exit code. When the server wrote to stderr, the message ends with see the local log for its stderr., and the last stderr lines are logged locally at WARNING on the maivn.mcp logger, with configured environment values and secret-looking values replaced by [REDACTED]. The stderr never reaches the model or the platform. Run the server's command by hand to see the full error.

#The API rejected the request

Error: MaivnHTTPError, for example mAIvn API returned 401: Authentication required.

Cause: The API answered with a non-2xx status. Every such reply carries a machine code, and exc.status_code, exc.code, exc.reason, exc.fields and exc.retry_after hold the parts. Branch on exc.code, not on the message text.

StatuscodeWhat to do
401authentication_failedSupply a valid key. See Authentication.
403authorization_failedYour key is valid but not allowed to do this. Check the project and operation.
403legal_acceptance_requiredAccept the required legal agreements in the Portal, then retry.
403memory_persistence_disabledYour team's memory policy has memory off or no storage allowed. Change the policy in the Portal, then retry. See Portal Memory Management.
422validation_failedFix the request. exc.fields names each field and what is wrong with it.
429rate_limitedWait exc.retry_after seconds, then retry.
variesplan_limit_exceededA plan limit is reached. The error is a PlanLimitExceededError with meter, limit, used and period_resets_at.
503memory_policy_unavailableThe platform could not read your team's memory policy, so the memory write was not stored. Retry.
502, 503, 504service_unavailable, timeoutRetry with backoff if the operation is safe to repeat.

Other statuses use the generic codes bad_request, not_found, conflict and internal_error. See Errors & Exceptions for the reply shape.

#A run ends with MaivnSDKError

Error: MaivnSDKError raised from invoke(), with a message such as structured_output_invalid_json or durable_event_refused.

Cause: The run reached a terminal error event. When the platform sends only a stable code, the exception message is that code.

Checks:

  1. Read exc.error_code, exc.session_id and exc.root_event_id. Include them in any support request.
  2. structured_output_invalid_json and contract_validation_failed mean the output did not match the expected schema. Check the answer model and field descriptions.
  3. durable_event_refused raises DurableBoundaryRefusedError (a MaivnSDKError subclass). Its refused_path names the field that still carried a private value. Check your private data declarations.
  4. Inspect the session before submitting the work again. The run may already have executed tools.
  5. max_iterations_exceeded means the run used every tool-calling cycle that max_cycles allowed, plus the tool-free answer turn after them, without finishing. Raise max_cycles (the platform never runs more than 20), or split the task. See Capping model-loop cycles.
  6. thread_user_mismatch means the thread belongs to another user_id. Continue it as its owner, or start a new thread.

#Memory retrieval returns no hits

Symptoms:

  • Follow-up turns do not recall prior details
  • memory_retrieved appears with low/zero hit count

Checks:

  1. Reuse the same thread_id across turns.
  2. Confirm memory is enabled (memory_config.enabled=True, or omit it and rely on scope defaults).
  3. Confirm retrieval is enabled via memory_config.level (glimpse, focus, or clarity).
  4. Check your team's memory policy in the Portal. With the memory switch off, runs neither recall nor store. A retention window hides records older than it.
  5. If testing immediately after a seed turn, wait briefly and retry (indexing is async).

#memory_indexed not observed

Cause (common):

  • Persistence not enabled at effective policy level, or write path was downscoped by config.

Checks:

  1. Confirm memory is enabled, its level is not none, and persistence_mode is not persist_none.
  2. Confirm memory_config.level is not downscoped by policy.
  3. Confirm your team's memory policy permits the persistence you asked for. The policy's persistence ceiling lowers a run's persistence_mode, and No storage stores nothing. A team that never saved a policy shows Not configured and uses your own settings.
  4. Inspect enrichment stream for memory_indexing/memory_indexed events.

#Context still too large in long threads

Checks:

  1. Keep prompts focused and avoid repeated full-history payloads when not needed.
  2. Automatic conversation compaction is not available. The recent-history tail is bounded; keep essential facts explicit or start a new thread with an application-provided summary. See History and run limits.
  3. Memory retrieval can add relevant context, but it does not guarantee complete recall of messages outside that tail.

#Debugging

#Enable Event Tracing

See detailed execution information:

Python
response = agent.invoke(messages, verbose=True)

Since maivn 3.1.0, agent.events().invoke(...) prints nothing unless you pass auto_verbose=True.

#Configure Logging

Send SDK log output to a file:

Python
from maivn import configure_logging

logger = configure_logging('logs/maivn.log')  # creates the logs/ folder

#Check Log Level

Attach a standard Python logging handler for console output:

Python
import logging
from maivn import get_logger

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
get_logger().addHandler(handler)

The SDK logger does not read MAIVN_LOG_LEVEL. See the logging reference for handler configuration and file output.

#Inspect Tool Registration

List registered tools:

Python
for tool in agent.list_tools():
    print(f'{tool.name}: {tool.description}')
    print(f'  final_tool: {tool.final_tool}, always_execute: {tool.always_execute}')
    print(f'  tags: {tool.tags}')

#Compile Tools Without Executing

Inspect the local tool metadata and model-visible schemas:

Python
tools = agent.compile_tools()
print(f'Tools: {len(tools)}')
for tool in tools:
    print(tool.name, tool.input_schema)

#FAQ

#How do I reuse a thread for multi-turn conversation?

Python
# First turn
response1 = agent.invoke(
    [HumanMessage(content='Hello')],
    thread_id='my-conversation',
)

# Second turn (same thread_id)
response2 = agent.invoke(
    [HumanMessage(content='Follow up')],
    thread_id='my-conversation',
)

#Why isn't my tool being called?

  1. Check the description - Make it clear when the tool should be used
  2. Check the system prompt - Guide the LLM to use your tools
  3. Use event tracing - Run with agent.invoke(..., verbose=True) to inspect decisions
  4. Check tool registration - Use agent.list_tools()

#How do I handle large tool catalogs?

Register only the tools the agent needs, filter toolsets at registration, or use targeted_tools for a specific invocation. Selected tools' dependencies are also included. See the tools guide.

#How do I cancel a running invocation?

Use client.cancel(session_id) or await client.acancel(session_id) to request cancellation of an active server invocation. Use its session ID, not the thread ID. Closing an HTTP connection or receiving a timeout does not send this request.

#Why are my private data values appearing in logs?

Private-data injection is not a general-purpose log scrubber. The SDK's Python logger does not sanitize arbitrary application log messages. Check tool code, exception messages, and HTTP debug logging for raw values before sharing logs. If a documented redaction path exposes a value, report the affected path with a sanitized reproduction. See the private-data guide.

#Environment Checklist

Before debugging, verify:

  • [ ] An API key is available to your app (api_key=, MAIVN_API_KEY, or a selected key file)
  • [ ] MAIVN_BASE_URL is unset for the hosted API, or points at your local stack
  • [ ] The API is reachable from your network
  • [ ] Python 3.10 or newer, and maivn version prints the release you expect
  • [ ] Dependencies installed (uv sync or pip install maivn)

#Getting Help

If you're still stuck:

  1. Check the API Reference
  2. Review the Guides
  3. Run a known-good app in mAIvn Studio and compare event traces
  4. Inspect a failing run from the Executions explorer in the developer portal

#See Also

#Support

For account, billing or runtime help, contact hello@maivn.io. Chad is the initial support and incident escalation owner. You can also use the developer Portal to review your account and usage, and to see which billing actions are available.

Include the SDK version, selected deployment, approximate time with timezone, organization/project identifiers, and the session or request ID when available. Add a short reproduction and a redacted error message. Keep API keys, payment details, private values and full customer transcripts out of support messages.

For retention or deletion questions, identify the record type and scope you need help with. Confirm the supported procedure before relying on a retention period or deletion outcome.