[!IMPORTANT]
Public beta. Managed Deep Agents is in public beta. The PyPI package API
and managed runtime contract may change. See the
docs
for getting started and updates.
managed-deepagents is the PyPI package for authoring Managed Deep Agents in
Python. It includes:
define_deep_agent, the Python authoring contract for managed agents.
define_schedule, the Python contract for managed cron schedules.
mda, the CLI used to build and deploy your agent to LangSmith.
managed_deepagents.runtime, the runtime helper used by generated managed
entry modules.
Install
uv tool install managed-deepagents
[!NOTE]
Private beta: dev releases only. We currently publish only PEP 440
pre-release (dev) versions and no stable version yet. uv skips pre-releases
by default unless they are allowed explicitly:
uv tool install --prerelease allow managed-deepagents
This package requires Python 3.9 or newer. Each platform wheel bundles the
prebuilt mda binary for its OS and CPU architecture and exposes it through the
mda console script. This PyPI-installed CLI scaffolds and compiles Python
projects only and vendors the Python runtime bundled with this wheel.
To start a new project, run mda init. In a terminal, the CLI asks you to name
the agent:
mda init
Run mda init -i to initialize your agent interactively and optionally hand it
off to a coding agent to build:
mda init -i
Choose a coding agent to continue in the new project, or select View raw
prompt to copy the setup instructions.
For coding agents and other headless use, pass the project name:
mda init my-agent
mda init can shape the project up front — --instructions "..." (or
--instructions-file <path>) writes the system prompt, --model <spec> picks
the model, --memory agent opts into deployment-shared durable memory,
--no-sandbox leaves out the sandbox, and -c slack (also --channel /
--channels) writes channels/slack.py. Every new project includes an
identity.py that explicitly selects auth.langsmith_api_key() authentication.
Evaluate
Managed Deep Agent evals run in Harbor. Install uv and Docker before running
them.
-
From the project root, initialize the eval workspace:
mda evals init -i
-
Follow the coding-agent prompt to author tasks directly under
evals/<task>/. The CLI creates the user-owned evals/harbor-job.json once
and preserves later edits. .mda/evals/ is generated.
A task may include an authored evals/<task>/identity.json fixture. It
requires a non-empty user.id; user.kind, user.email, and top-level
groups, claims, and source.provider are optional. Keep it with the
task, not in generated .mda/evals/.
-
Export LANGSMITH_API_KEY, LANGSMITH_WORKSPACE_ID when your credentials
require it, and the model or tool credential variables used by the agent.
-
From the same project root, run the pinned Harbor 0.21.0 command included at
the end of the coding-agent prompt. The command loads MDAJobPlugin and
LangSmithPlugin. It uses POSIX syntax on macOS/Linux and PowerShell on
native Windows.
-
From the same project root, inspect results:
uv run --python 3.12 --with 'harbor[langsmith]==0.21.0' harbor view .mda/evals/jobs
MDAJobPlugin compiles a fresh eval artifact at every Harbor job start.
This POC keeps MDA's custom Harbor adapter; migration to Harbor's built-in
LangGraph agent is deferred.
Define an Agent
Create an agent.py that defines an agent:
from managed_deepagents import define_deep_agent
# The system prompt comes from instructions.md next to this file.
agent = define_deep_agent(
name="research-assistant",
model="openai:gpt-5.5",
tools=[query_db],
)
define_deep_agent requires name and supports the create_deep_agent options except the platform-owned backend, store, checkpointer, system_prompt, and memory fields. Static agents use instructions.md and all discovered skills.
Export a sync or async factory as agent to select configuration per run:
from managed_deepagents import ManagedServerRuntime, define_deep_agent
def agent(runtime: ManagedServerRuntime):
execution = runtime.execution_runtime
ctx = execution.context if execution is not None else {}
return define_deep_agent(
name="support",
model=(
"openai:gpt-5-mini"
if isinstance(ctx, dict) and ctx.get("tier") == "fast"
else "openai:gpt-5.5"
),
)
The factory can select tools, middleware, instructions, skills, MCP definitions,
a sandbox, and memory. Omitted selections use project resources. None disables
an instruction, skill, MCP, sandbox, or memory selection for that run. Empty
strings and arrays remain explicit selections. Select memory with define_memory(...);
selected memory cannot use allow. Root memory.py remains the fallback.
On direct runs, execution_runtime.context is application context or None.
On channel runs, it is None; read the conversation from runtime.thread.
ManagedServerRuntime[AppContext] preserves the application's context type.
It extends the native langgraph_sdk.runtime.ServerRuntime variants with managed
fields. access_context identifies the Agent Server operation that called the
factory.
During inspection, execution_runtime is None. Keep the factory repeatable and
preserve graph structure and schemas. MDA skips managed resource reads and
allocation. Context is application data; tools must check authorization.
mda build reads the inline literal name without calling the factory. Install
all model integrations the factory can select.
To authenticate SDK and API requests with a LangSmith workspace key while
retaining MDA's thread and store authorization, declare it explicitly:
identity = define_identity(auth=auth.langsmith_api_key())
Clients send the key as x-api-key. LangSmith Cloud supplies the verification
endpoint and tenant configuration; do not add those platform-owned values to
the project .env.
A personal access token identifies the LangSmith user who owns it. That caller
is a person: it can use user-owned connections, is eligible for user memory
under the user memory policy, and resolves to the same Agent Auth principal as
that user in deployed Studio, so a connection made in Studio also works over the
API. A service key carries no user and stays one workspace service principal, so
every caller that shares it shares its threads and cannot use user-owned
connections or user memory. To act for many end users from one server, use a
trusted backend or validated-token identity instead.
On deploy, Context Hub stores harness files (instructions.md, skills/**). A
root memory.py enables agent, assistant, and user memory independently:
from managed_deepagents import MemoryLayer, define_memory
memory = define_memory(
agent=MemoryLayer(),
assistant=MemoryLayer(),
user=MemoryLayer(),
)
Omit a layer to disable it. A layer with no allow callback uses its default
policy. Agent memory is shared across callers and is available by default.
Assistant memory is available by default and shared only by runs of the same
assistant in this deployment. It requires the trusted assistant identity supplied
by Agent Server; missing identity fails the run instead of using shared memory.
Neither authored context nor a custom key callback can select another assistant.
User memory requires a trusted person and defaults to managed Slack one-to-one
DMs (the original provider event has channel_type == "im"). Shared
conversations, missing event data, and direct API runs get no user mount unless
an authored policy allows it.
For compatibility, an autodiscovered root declaration can still use a sync or
async allow(context) callback to replace its default policy. allow is
deprecated and emits a warning; prefer selecting memory from a dynamic agent:
from typing import TypedDict
from managed_deepagents import ManagedChannelContext, MemoryLayer, define_memory
class Context(TypedDict):
remember: bool
def allow_memory(context: Context | ManagedChannelContext) -> bool:
return not isinstance(context, ManagedChannelContext) and context.get("remember") is True
memory = define_memory(
agent=MemoryLayer(),
user=MemoryLayer(allow=allow_memory),
)
Verified Studio users get the declared user memory layer without calling its
policy. Under mda dev, a personal LangSmith API key resolves the developer's
langsmith-dev Agent Auth principal; memory stays in .mda/__contexthub__.
Deployed Studio uses the verified LangSmith user ID and stores memory in Context Hub.
When evaluated, each callback runs once before memory mounts, including interrupt
resumes. Returning false removes only that layer's mount and hot memory for
the run. If the context cannot satisfy the policy schema, MDA denies that layer
without calling its policy. An error from the callback still fails the run.
User policies cannot grant access to another
person's memory or grant user memory to a service principal. Build, schema, and
state inspection do not call memory policies.
The legacy scope option remains supported. Do not combine it with agent, assistant, or
user.
Permitted hot memory is loaded once per run, on the first model call, and reused
for subsequent model calls. It is not saved in thread state. This keeps the graph structure
stable and prevents a later denied run from loading saved memory. A missing
hot file stays empty until the first memory write.
The agent layer is mounted at /memories/agent/. The assistant layer mounts
/memories/assistant/ from an opaque per-deployment, per-assistant Context Hub repo.
Assistant memory is separate from deployment-shared agent memory and per-person
user memory. The user layer requires
identity.py and is mounted from an opaque per-user Context Hub repo at
/memories/user/, keyed on the trusted caller principal. Each mount's
AGENTS.md is injected every turn; other files are read on demand. Deploy never
overwrites existing memories. A project without memory.py mounts no durable
memory.
Mounting your own backends
routes mounts Deep Agents backends at path prefixes, as
CompositeBackend(routes=...) does. A path under a prefix goes to that backend
with the prefix stripped; every other path keeps the managed backend.
from deepagents.backends import StoreBackend
from managed_deepagents import define_deep_agent
agent = define_deep_agent(
name="research-assistant",
routes={
"/documents/": StoreBackend(namespace=lambda _rt: ("documents",)),
},
)
Prefixes must be absolute directories ("/documents/") and cannot overlap the
paths MDA mounts itself: /instructions.md, /skills/, and /memories/.
Routes serve the file tools; shell commands in a sandbox do not see them.
Async subagents
Every Python agent can run its general-purpose subagent either way: blocking
through task, or in the background through start_async_task. The agent
picks per task, so there's nothing to declare. MDA builds the background copy
as an extra graph, <agent>--general-purpose, from your own general-purpose
subagent if you declare one (not a fork), keeping its skills, or else from the
Deep Agents default, which loads the agent's skills. Like any async subagent, it can also be run directly as its own assistant, with
the agent's tools but not its instructions or middleware. mda eval runs the
blocking one only.
Mark a subagent with "async": True to run it in the background. MDA builds it
as its own graph in the same deployment, and the agent starts it, checks on it,
and reads its result while it keeps working:
agent = define_deep_agent(
name="lead",
subagents=[
{
"name": "researcher",
"description": "Researches a topic in the background",
"system_prompt": "You research topics thoroughly.",
"async": True,
}
],
)
The subagent runs under the caller's identity and uses the project's sandbox,
identity, and connector declarations. When it leaves model, tools,
permissions, or interrupt_on unset, it uses the agent's. It does not inherit
the agent's middleware or memory. Like a sync subagent, it loads only the skills
its skills key names: "skills": ["/skills/"] gives it the agent's skills.
When the project has a sandbox, the subagent works in the sandbox of the agent
that started it, so both see the same files. MDA first checks that the subagent
run's caller owns the starting agent's thread (a Slack conversation or a user),
so a run can't name another caller's sandbox. The subagent only refreshes
credentials in the shared sandbox; it never reruns workspace setup there or
deletes it. If the starting agent hasn't created its sandbox yet, the subagent
creates it, and the starting agent then uses that same sandbox.
When the subagent pauses for approval, the agent sees the task as waiting. If the
agent was started from a Slack channel, the approval shows in that Slack thread,
and the answer there resumes the subagent. Otherwise, answer it in the subagent's
own thread. When a task finishes, the agent's reply about it is posted to the
same Slack thread. A subagent's runtime.thread is its starting agent's thread,
so its tools and middleware can also post to that Slack thread through
runtime.thread.origin.channel, for example to show progress. The subagent's
own answer is not posted.
With tracing on, a subagent's runs appear in the starting agent's trace, under
the call that started it. Nesting follows the trace headers on the request, so
any caller allowed to start runs on this deployment can place its run inside
another trace in the same workspace.
Each async subagent is its own graph, so any caller allowed to start runs on
this deployment can also run it directly, as themselves. It doesn't get the
agent's middleware, so don't rely on the agent's middleware to guard the tools
it shares with a subagent, and don't give it looser interrupt_on or permissions
than the agent that starts it.
Write async subagents in agent.py as dict literals, or names bound to one, so
the build can find them without running your code. Other fields can come from
code, as long as name and "async" come after any **spread:
{**worker_spec("low"), "name": "low", "async": True}. mda build warns about
subagent entries it can't read.
Run context and channels
The runtime separates application data, trusted caller information, and the
current channel delivery:
runtime
.context // Application data on direct runs; None on channel runs
.server_info // Trusted caller and server information
.channel // Present for a managed channel delivery
.name // Configured channel name
.provider // Provider label, such as slack
.event // Typed MDA delivery; no internal routing
.raw_event // Optional original provider payload
.post(...) // Present when sending is supported
.backend // Present when a sandbox is configured
.schedules // Create and manage schedules for this run's caller
API callers supply application data through Agent Server's context parameter:
await client.runs.create(
thread_id,
assistant_id,
input={"messages": [{"role": "user", "content": "Hello"}]},
context={"remember": True},
)
Direct API runs use your authored context_schema and native LangGraph context
validation. On channel runs, tools, middleware, and authored factories receive
None as context. Use runtime.thread.origin.channel.event for the typed event
and runtime.thread.origin.channel.raw_event for optional provider data. The application schema
stays on the graph, but its required fields do not apply to channel runs.
Supplying a channel field in a direct API call does not establish a trusted
channel source.