Building Custom Python Agents
Not every agent is built on LangGraph, CrewAI, Google ADK, or Strands Agents. AgentVisor™ is a framework-agnostic runtime that confines AI agents: any Python process that reads a JSON object from stdin and writes a JSON object to stdout runs under the full stack — sandbox isolation, policy enforcement, credential brokering, Temporal-backed durability, and the HTTP API — with no Go code required.
This guide covers building custom Python agents for AgentVisor using the custom-python
framework provider.
When to Use This
Reach for custom-python when your agent uses a proprietary or in-house framework, a framework
not yet natively supported (see Supported Frameworks), or when you're
wrapping an existing Python program that already exposes a request/response entrypoint. If your
framework is LangGraph, CrewAI, Google ADK, or Strands Agents, use its dedicated provider instead — those providers
add framework-specific schema discovery and I/O handling on top of the same underlying contract.
Prerequisites
- Python 3.10+
- AgentVisor CLI installed
Basic Structure
Every custom-python project for AgentVisor needs:
- An entrypoint script: A Python file implementing the stdin/stdout JSON contract
mav-agent-config.yaml: Selects thecustom-pythonprovider and points at your entrypoint.agentvisor/schema.json: A hand-written manifest declaring your agent(s)requirements.txt: Python dependencies (omit or leave empty if you only use the standard library)
Unlike LangGraph (langgraph.json), CrewAI (crewai.yaml), and ADK (agent.yaml), there is no
discovery file that triggers automatic provider selection — custom-python must always be named
explicitly in mav-agent-config.yaml.
The Agent Process Contract
This is the part every built-in provider supplies through its framework's runner. Building a
custom-python agent means implementing it yourself:
-
Input arrives as a single JSON object on stdin, then stdin closes (EOF). Nothing is passed via
argv. -
Output must be a JSON object on the last line of stdout. Only that final line is read; every earlier stdout line is discarded, whatever it contains. Two consequences to design around:
- Anything your process prints to stdout after the result (a trailing log line, a library banner at exit) replaces it as the "last line" and hides the result.
- If the last line is not a JSON object, the run still succeeds, with a
nulloutput and no error. A malformed or missing result is not reported as a failure.
Send logs to stderr, never stdout.
-
The maximum stdout line length is 10 MB.
-
Exit codes:
0— success2— cooperative shutdown: a clean exit between supersteps. The workflow replays from the last checkpoint. This is not an error — reserve it for agents that checkpoint progress and voluntarily yield control (see Checkpoints below).- anything else — failure. The last 50 lines of stderr are attached to the error surfaced to the caller.
-
Stderr is forwarded to the host as structured log entries (
logger_name="agent.stderr"). -
AgentVisor strips its own control markers out of the input object before your process sees it and delivers them instead as environment variables: the streaming flag becomes
AGENTVISOR_STREAM/AGENTVISOR_STREAM_MODEand the run ID becomesAGENTVISOR_RUN_ID(see Environment Your Process Receives).
A complete, minimal entrypoint:
import json
import sys
def run_agent(data: dict) -> dict:
"""Invoke your framework here."""
message = data.get("message", "")
return {"reply": f"You said: {message}"}
def main() -> int:
raw = sys.stdin.read()
data = json.loads(raw) if raw.strip() else {}
# Logs belong on stderr — stdout is reserved for the final JSON result.
print(f"received input: {data}", file=sys.stderr)
result = run_agent(data)
# This MUST be the last line written to stdout, and MUST be valid JSON.
print(json.dumps(result))
return 0
if __name__ == "__main__":
sys.exit(main())
Declaring Your Agents
Because custom-python has no framework-specific discovery file to introspect, agent schemas come
from a hand-written manifest at .agentvisor/schema.json in your project directory:
{
"version": "1.0",
"graphs": {
"my_agent": {
"name": "my_agent",
"description": "What this agent does.",
"input_schema": {
"type": "object",
"properties": {
"message": { "type": "string" }
},
"required": ["message"]
},
"output_schema": {
"type": "object",
"properties": {
"reply": { "type": "string" }
},
"required": ["reply"]
},
"metadata": {}
}
}
}
The top-level key is graphs — a legacy name shared with the LangGraph provider's manifest format.
The manifest is framework-agnostic: every entry is treated as a plain agent definition, with no
LangGraph semantics. A manifest that is valid JSON but lacks the graphs key (or has the wrong
shape) is accepted without error and simply declares no agents. Each entry's key (my_agent above) is the agent ID used in API
calls (POST /threads/{id}/runs?agent=my_agent, or the sole agent when only one is defined).
input_schema/output_schema are standard JSON Schema and drive both API validation and the
OpenAPI docs.
Without a manifest, the agent still runs end-to-end — agent_id isn't validated host-side — but
GET /agents is empty, no MCP invoke_agent tool is generated for it, and its A2A agent card has
no skills. The manifest is what makes the agent discoverable, not what makes it run.
custom-python performs no dynamic schema extraction — the manifest is the sole source of truth.
See Schema Discovery below.
docker and gvisorUnder --sandbox=docker and --sandbox=gvisor the manifest is currently not picked up, so
GET /agents returns an empty list (and the MCP and A2A entries above are missing) even though the
agent runs correctly. Discovery works under --sandbox=none. Invoke the agent by its ID in the
meantime.
Wiring It Up
Select the provider and point it at your entrypoint in mav-agent-config.yaml:
# mav-agent-config.yaml
framework:
provider: "custom-python"
command: ["python3", "main.py"]
command is required for custom-python — unlike langgraph, crewai, adk, and strands,
there is no default runner module to fall back to. Omitting it fails at startup, before any run
is attempted, with:
framework provider "custom-python" has no default runner: set framework.command in mav-agent-config.yaml
Installing Your Framework
List your dependencies in requirements.txt as usual:
# requirements.txt
my-proprietary-framework>=1.0.0
Don't include agentvisor — it's automatically available in the guest environment. If your
framework needs native or system-level dependencies (not installable via pip), drop a Dockerfile
in your project's source directory — a source-dir Dockerfile always takes precedence over
AgentVisor's generated template when building the guest image.
Using AgentVisor Services
This is the real payoff of running under custom-python instead of a bare script: everything the
built-in frameworks get, your framework gets too, unchanged, over the same
$AGENTVISOR_AGENT_SOCKET connection.
Checkpoint, Store, State, and Streaming
from agentvisor import checkpoint, store, stream
# Durable state across runs, backed by the Temporal workflow
checkpoint_id = checkpoint.save("progress", {"step": 3})
saved = checkpoint.load(checkpoint_id)
# Key-value memory that persists across threads (requires AGENTVISOR_STORE_PROVIDER)
store.put("myapp", "user-prefs", {"theme": "dark"})
prefs = store.get("myapp", "user-prefs")
# Real-time SSE chunks delivered to /threads/{id}/runs/{runId}/stream
stream.emit_chunk({"token": "partial output"}, chunk_type="token")
MCP and A2A
from agentvisor import mcp, a2a
tools = mcp.list_tools("fetch") # name matches mcp.servers[].name in agentvisor.yaml
result = mcp.call_tool("fetch", "fetch_url", {"url": "https://example.com"})
card = a2a.get_agent_card("analyzer") # name matches a2a_gateway.agents[].name
task = a2a.send_task("analyzer", a2a.text_message("Analyze this."))
Logging and Tracing
Plain logging.getLogger(__name__) calls — and third-party library loggers — are captured
automatically and forwarded to the host via gRPC, no agentvisor import required:
import logging
logger = logging.getLogger(__name__)
logger.info("processing request", extra={"step": 3})
HTTP requests your framework makes go through HTTP_PROXY/HTTPS_PROXY automatically (both are
injected into the environment — see below), so outbound calls are policy-enforced and eligible for
credential substitution without any code changes. TRACEPARENT/TRACESTATE are injected for W3C
trace propagation if your framework instruments HTTP calls with an OTEL SDK.
Environment Your Process Receives
AgentVisor injects the following per-agent, with its own values always winning over anything a lower-precedence source sets:
| Variable | Purpose |
|---|---|
AGENTVISOR_AGENT_SOCKET | Unix domain socket for checkpoint/store/stream/mcp/a2a calls |
AGENTVISOR_THREAD_ID, AGENTVISOR_RUN_ID, AGENTVISOR_AGENT_NAME, AGENTVISOR_EXECUTION_ID | Identity context for the current invocation |
AGENTVISOR_SOURCE_DIR | Path to your agent's source directory inside the sandbox |
HTTP_PROXY, HTTPS_PROXY, NO_PROXY | Route outbound HTTP through the policy-enforcing proxy |
SSL_CERT_FILE, REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, NODE_EXTRA_CA_CERTS | Trust the proxy's ephemeral CA for TLS termination |
TRACEPARENT, TRACESTATE | W3C trace context propagation |
HOME | /home/agent — stable, writable home directory |
AGENTVISOR_STREAM, AGENTVISOR_STREAM_MODE | Set when the run was invoked in streaming mode (the flag is stripped from the input object and delivered as env instead) |
In hardened sandbox modes (env_curation enabled — the default for docker and gvisor), only an
allowlist of system variables (PATH, HOME, VIRTUAL_ENV, LANG, LC_ALL,
PYTHONDONTWRITEBYTECODE, PYTHONUNBUFFERED, PYTHONPATH, plus terminal variables) is inherited
from the guest runtime's own environment, on top of which the table above is always injected. To
forward additional host environment variables into the sandbox, use
guest.environment_passthrough in agentvisor.yaml; to set agent-specific variables regardless of
sandbox mode, use framework.env in mav-agent-config.yaml:
# mav-agent-config.yaml
framework:
provider: "custom-python"
command: ["python3", "main.py"]
env:
MY_FRAMEWORK_LOG_LEVEL: "debug"
Variables starting with AGENTVISOR_GUEST_ are always blocked from reaching the agent process,
regardless of source. See Environment Configuration for the
full precedence rules.
What You Give Up
Compared to the built-in providers, custom-python trades framework-specific conveniences for
generality:
- No
--debugsupport. Debug mode integrates with framework-specific runners (debugpy,pydevd) wrapping the default runner module. Sincecustom-pythonhas no default runner —framework.commandalways takes over — debug mode is suppressed with a logged warning, exactly as it would be for the other Python providers whenframework.commandoverrides their default command too. - No automatic schema extraction. The built-in Python providers can introspect your code to
generate schemas dynamically.
custom-pythondoes not — the.agentvisor/schema.jsonmanifest is the only source of agent definitions, and you maintain it by hand.
Provider Selection
custom-python is never selected implicitly — there is no discovery file for it to key off.
Name it explicitly:
framework section | framework.provider | Result |
|---|---|---|
| Absent | — | Falls through to langgraph.json/agent.yaml/crewai.yaml detection, or errors |
| Present | "custom-python" | custom-python provider |
See Provider Selection in the Configuration Reference for the complete decision table across all providers.
Schema Discovery
The built-in Python providers discover agents in three tiers: a build-time manifest, then dynamic
extraction from your code, then a framework discovery file. custom-python uses only the first:
- Hand-written manifest (
.agentvisor/schema.json) — the sole source of truth; see Declaring Your Agents above. - Dynamic extraction — not performed. The extractor only understands the built-in frameworks' conventions, so it is skipped rather than risk misreading your project.
- Discovery-file fallback — unavailable (there is no discovery file to fall back to).
If the manifest is missing or unreadable, the agent list is empty; a warning is logged.
Testing Locally
# Start development services
temporal server start-dev
# Run the agent (no sandbox for local dev)
agentvisor serve ./my-custom-agent --sandbox=none
# Create a thread
THREAD=$(curl -sX POST http://localhost:8090/threads | jq -r '.thread_id')
# Invoke the agent
curl -sX POST "http://localhost:8090/threads/$THREAD/runs?wait=30s" \
-H "Content-Type: application/json" \
-d '{"input": {"message": "Hello!"}}' | jq '.output'
Working Example
See the Minimal Agent example — the smallest possible
custom-python agent: a single script implementing the bare stdin/stdout contract, with a clearly
marked seam (run_agent()) where you plug in your own framework.
Graduating to a Native Provider
If your framework grows beyond what a command override and a hand-written manifest comfortably
support — you want implicit provider selection based on your own discovery file, dynamic schema
extraction, PTY-based interaction, or a non-Python runtime — the next step is a small Go framework
provider. Contact us at support@manetu.com to discuss your use case.
Related Guides
- Project Anatomy: Full
mav-agent-config.yamlreference - Environment Configuration: Environment variable precedence and passthrough
- Agent Logging: Structured logging for agent code
- MCP Gateway: Configuring MCP servers for agent tool access
- Policy Configuration: Authorization policies for agent resource access
- Supported Frameworks: Overview of all supported agent frameworks