Metadata-Version: 2.4
Name: managed-deepagents
Version: 0.8.0.dev4
Summary: Managed Deep Agents — the define_deep_agent authoring interface plus the CLI that compiles and deploys a code-first Deep Agent repository to a managed LangGraph runtime.
Author: LangChain
License: MIT
Project-URL: Homepage, https://github.com/langchain-ai/managed-deepagents-sdk
Project-URL: Repository, https://github.com/langchain-ai/managed-deepagents-sdk
Keywords: langchain,langgraph,deepagents,agents,cli
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.13.5
Provides-Extra: test
Requires-Dist: cryptography>=50.0.1; extra == "test"
Requires-Dist: langchain-core>=1.6.2; extra == "test"
Requires-Dist: pyjwt[crypto]>=2.13.0; extra == "test"
Requires-Dist: pytest>=9.1.1; extra == "test"
Requires-Dist: starlette>=1.6.0; extra == "test"
Dynamic: license-file

<!-- markdownlint-disable MD033 MD041 -->

<div align="center">
  <a href="https://docs.langchain.com/langsmith/python/managed-deep-agents-overview">
    <img alt="Managed Deep Agents logo" src="https://raw.githubusercontent.com/langchain-ai/managed-deepagents/main/logo.png" width="70%">
  </a>
</div>

<div align="center">
  <h3>Python authoring package and CLI launcher for Managed Deep Agents.</h3>
</div>

> [!IMPORTANT]
> **Public beta.** Managed Deep Agents is in public beta. The PyPI package API
> and managed runtime contract may change. See the
> [docs](https://docs.langchain.com/langsmith/python/managed-deep-agents-overview)
> 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

```bash
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:
>
> ```bash
> 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:

```bash
mda init
```

Run `mda init -i` to initialize your agent interactively and optionally hand it
off to a coding agent to build:

```bash
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:

```bash
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.

1. From the project root, initialize the eval workspace:

   ```bash
   mda evals init -i
   ```

2. 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/`.
3. Export `LANGSMITH_API_KEY`, `LANGSMITH_WORKSPACE_ID` when your credentials
   require it, and the model or tool credential variables used by the agent.
4. 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.
5. From the same project root, inspect results:

   ```bash
   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`:

```python
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 a static `name` (LangGraph assistant id and default LangSmith deployment name) and otherwise accepts the [`create_deep_agent`](https://reference.langchain.com/python/deepagents/graph/create_deep_agent) keyword surface minus the managed keys: `backend`, `store`, `checkpointer`, `memory`, `skills`, and `system_prompt`. Those are provided by the managed runtime when your agent is deployed. Write the system prompt in `instructions.md` next to `agent.py`; the CLI embeds it at deploy time.

To authenticate SDK and API requests with a LangSmith workspace key while
retaining MDA's thread and store authorization, declare it explicitly:

```python
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`.

On deploy, Context Hub stores harness files (`instructions.md`, `skills/**`). A
root `memory.py` enables agent and user memory independently:

```python
from managed_deepagents import MemoryLayer, define_memory

memory = define_memory(
    agent=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.
User memory requires a trusted person and defaults to managed Slack one-to-one
DMs (`event.channel_type == "im"`). Shared conversations, missing event data,
and HTTP runs get no user mount unless an authored policy allows it.

Either layer can use a sync or async `allow(context)` callback to replace its
default policy:

```python
from typing import TypedDict
from managed_deepagents import MemoryLayer, define_memory


class Context(TypedDict):
    remember: bool


def allow_memory(context: Context) -> bool:
    return context.get("remember") is True


memory = define_memory(
    agent=MemoryLayer(),
    user=MemoryLayer(allow=allow_memory),
)
```

Each callback runs once before memory mounts on each run, 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 either policy.

The legacy `scope` option remains supported. Do not combine it with `agent` or
`user`.

User hot memory and agent hot memory with an `allow` policy are loaded for each
model call. They are 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 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.

## Run context

The managed channel handler passes the provider and original event as run context:

```json
{
  "provider": "slack",
  "raw_event": {
    "type": "message",
    "channel": "D123",
    "channel_type": "im",
    "user": "U123",
    "text": "Hello",
    "ts": "1712345678.000002"
  }
}
```

`raw_event` is `ChannelEvent.raw_event`, preserved as received. For Slack, it is
the inner event object, including extra provider fields it excludes the outer
webhook envelope and HTTP headers. Interrupt resumes currently omit the raw
event, so their context contains only `provider` and the default memory policy
does not mount user memory. The handler verifies its service credential and
caller identity before starting a run.

`normalized` is MDA's provider-neutral view of the same delivery, present when
MDA can build one. A `user_prompt_response` delivery — a click or submission on
a prompt the app itself posted — normalizes to
`{ provider, action, value?, correlation_id? }`.
When the response answers a parked `interrupt()`, that same object is the resume
value, so one handler serves both the blocking and the fire-and-forget case.

With one interrupt parked, the answer resumes it. To stay unambiguous when
several may be parked at once, put the same id on the prompt you post and on
the value you pass to `interrupt()`, under `INTERRUPT_CORRELATION_KEY`; the
answer then arrives with a matching `normalized.correlation_id` and resumes that
interrupt exactly. Without it, several parked interrupts are refused rather than
guessed, because interrupt ids carry no ordering.

Run context is not authenticated. Any caller that can create a run can send
`context: { provider: "slack", raw_event: {...} }`, so treat it as corroborating
rather than proof. Gate on the trusted identity and use context only to refine,
which is what the default Slack DM policy does:

```python
identity.source.provider == "slack" and context.get("provider") == "slack"
```

An authored `allow(context)` replaces the default Slack rule. It can inspect
`context.provider` and `context.raw_event` for provider-specific decisions.

Custom frontends use the same Agent Server `context` parameter:

```python
await client.runs.create(
    thread_id,
    assistant_id,
    input={"messages": [{"role": "user", "content": "Hello"}]},
    context={"remember": True},
)
```

HTTP callers define their own context and use `allow(context)` to decide when
user memory is available. The example above works with the `remember` policy
shown earlier. Authentication still determines the memory owner. A policy that
always returns true is suitable only when every reply destination is appropriate
for the caller's personal memory.

`ManagedRunContext` types the managed channel fields. Keep your own `context_schema`
if needed; include `provider`, `raw_event` and `normalized` if your policy or tools use them,
because Agent Server can remove undeclared fields. MDA does not replace your
schema. Tools and middleware read the same supplied data through `runtime.context`.
The default Slack DM policy reads the original run context, before MDA applies
the authored schema. Your schema does not need to declare `provider` or `raw_event`
for that default policy.

Deployments use Agent Server `0.16.0.dev1`. Python `mda dev` passes run context
to graph factories and can evaluate both agent and user memory policies. User
memory still requires a trusted person and an allowed policy.

## Project Shape

```text
my-agent/
  agent.py              # named `agent` variable
  identity.py           # managed authentication (included by `mda init`)
  memory.py             # optional durable-memory declaration
  instructions.md       # managed system prompt
  pyproject.toml
  .env                  # local deploy secrets, never committed
  schedules/            # optional managed cron schedules
  tools/                # optional custom tools and MCP declaration
    mcp.py              # optional MCP server declaration
  middleware/           # optional middleware
  skills/               # optional skills synced to Context Hub
  sandbox/              # LangSmith sandbox (`mda init` includes this; delete to opt out)
```

The CLI copies your project files into the managed build and generates the entry
module that connects your definition to the hosted runtime.

The agent entry must live at the project root as `agent.py`.

## Define a Schedule

Create one file per schedule under `schedules/` and define a named `schedule`:

```python
# schedules/daily_digest.py
from managed_deepagents import define_schedule

schedule = define_schedule(
    cron="0 8 * * 1-5",
    timezone="America/Los_Angeles",
    prompt="Write the daily digest.",
)
```

`mda deploy` reconciles schedules as LangSmith cron jobs after the deployment is
live. Declarations must be statically serializable literals or top-level
constants; prompt schedules become user-message input, and stateless runs clean
up their temporary thread after completion.

## Sandbox

`mda init` scaffolds `sandbox/__init__.py` with a LangSmith sandbox. MDA only
enables the sandbox when that declaration is present — delete `sandbox/` to opt
out:

```python
from managed_deepagents import define_sandbox

sandbox = define_sandbox(
    idle_ttl_seconds=600,
)
```

If `sandbox/setup.sh` exists, `mda deploy` / `mda dev` bake it into a recipe
snapshot once; thread sandboxes clone that snapshot and do not re-run setup.
MDA owns sandbox naming, image/snapshot selection, reuse, and lifecycle.

Authored tools and middleware can use the Deep Agents backend interface at
`runtime.backend`. It is `None` when the project has no sandbox:

```python
from managed_deepagents import ManagedDeepAgentRuntime


def write_report(runtime: ManagedDeepAgentRuntime) -> None:
    if runtime.backend is None:
        raise RuntimeError("This tool requires a sandbox")
    result = runtime.backend.write("/workspace/report.txt", "Report ready")
    if result.error:
        raise RuntimeError(result.error)
```

The backend uses the standard Deep Agents file arguments and results: `ls`,
`read`, `write`, `edit`, `grep`, and `glob`. `delete` is optional and depends on
the installed backend. Use `upload_files` and `download_files` for binary data.
Python also has async methods such as `aread`, `awrite`, and `adelete`.
All paths refer to the current sandbox. Context Hub routes for skills and
memory are not part of this backend.

Private published images can declare registry credentials by environment
variable name; MDA creates or updates the deployment-owned Host registry:

```python
sandbox = define_sandbox(
    docker_image="ghcr.io/acme/agent-base:1",
    registry={
        "url": "ghcr.io",
        "username": "octocat",
        "password_env": "GHCR_TOKEN",
    },
)
```

Put `GHCR_TOKEN` in the project `.env` or process environment. Its value is
used only to reconcile the registry and never enters the build or snapshot.

## MCP Servers

Add `tools/mcp.py` to attach MCP servers. The file must define a module-level
`mcp`. By default, MDA exposes every tool loaded from each
declared server. In `mda dev`, an agent-owned connection reads from
`MDA_DEV_<SLUG>` with the slug uppercased and hyphens changed to underscores.
Hosted deployments resolve workspace connections from Agent Auth:

The old `connectors/mcp.py` file API remains available with a warning during
`0.7.x`. It will be removed in `0.8.0`.

```python
from managed_deepagents import define_mcp, connections

mcp = define_mcp(
    servers={
        "langchainDocs": {
            "transport": "http",
            "url": "https://docs.langchain.com/mcp",
            "include_tools": ["search", "fetch"],
            "connection": connections.get("docs-token", {"type": "agent"}),
        },
        "exa": {
            "transport": "http",
            "url": "https://api.smith.langchain.com/v1/managed-tools/servers/exa/mcp",
        },
    },
)
```

For this example, set `MDA_DEV_DOCS_TOKEN`.

A user-owned connection — `connections.get(slug, {"type": "user"})` — resolves
per caller (OAuth or opaque). Any runtime access interrupts the run when a grant
is missing, including access from a custom tool or middleware. Connector
declarations use the same behavior in a pre-run gate, so all known grants can be
requested before the first model call. This path works in `mda deploy` and
`mda dev` when `LANGSMITH_API_KEY` and `LANGSMITH_WORKSPACE_ID` are set and
the workspace connection rows exist. Signed-in Studio users are identified by
their LangSmith `ls_user_id`. Local development uses separate user connections
from deployed Studio. OAuth completes on
LangSmith’s platform callback URL. The local UI must show
`credential_authorization_required` and resume after the user connects.

When a LangSmith-managed OAuth MCP server needs authorization, the runtime
reports its connection URL; complete OAuth there, then retry the run. API-key
MCP servers require the caller to connect the key in LangSmith Tools before
invoking one of their tools.

Deploy the project first, then provision its connections with
`mda connections create`. Agent-owned opaque secrets are scoped to that
deployment, so the command refuses to create one before `mda deploy`.
`mda deploy` fails when a slug a project declares is missing from the
workspace.

Use `include_tools` or `exclude_tools` inside a server config to select a
subset. Tool names are raw MCP tool names before the managed `{server}__` prefix
is applied, so `"include_tools": ["search"]` on server `langchainDocs` exposes
`langchainDocs__search` when prefixing is enabled.

## CLI

Create a new project:

```bash
mda init my-agent
```

Build locally:

```bash
mda build ./my-agent
```

Run on the local LangGraph dev server:

```bash
mda dev ./my-agent
```

`mda dev` requires `uv` on `PATH`, but it resolves the local LangGraph dev
server automatically; you do not need to install a global `langgraph` command.

Deploy to LangSmith:

```bash
mda deploy ./my-agent
```

The generated build is written to `<root>/.mda/build` by default.

Common deploy options:

```bash
mda deploy ./my-agent --name my-agent-dev --deployment-type dev
mda deploy ./my-agent --workspace-id "$LANGSMITH_WORKSPACE_ID"
mda deploy ./my-agent --no-wait
```

Read the deployed agent's server logs:

```bash
mda logs ./my-agent
mda logs ./my-agent --lines 200 --level error
mda logs ./my-agent > agent.log
```

In a terminal `mda logs` streams new output until you press Ctrl-C. When the
output is piped or redirected it prints the most recent lines (1000 by default)
and exits.

Tear it down again:

```bash
mda delete ./my-agent
```

`mda delete` (alias `mda destroy`) removes the LangSmith deployment, the tracing
project created alongside it, the deployment's Context Hub repo (plus any legacy
per-user or org child memory repos left from older runtimes), and the managed
sandboxes the deployment created. It asks for confirmation first; pass `--yes`
to skip the prompt in scripts. Agent memory and thread history are not
recoverable afterwards.

Sandboxes are matched by name: the runtime names each one
`{deployment}--{digest}` of the thread id, which also lets a restarted
deployment re-adopt its existing sandbox instead of stranding it. Recipe changes
(`setup.sh` or bake base) produce a new deploy-time snapshot; live threads keep
their boxes until reclaim. Sandboxes created before this behavior existed are
unnamed and are left to
LangSmith's idle-stop and retention window.

Before deploying, make sure your model provider key such as `OPENAI_API_KEY`
or `ANTHROPIC_API_KEY` is available in the project `.env` or LangSmith
workspace secrets; a value exported in your shell is not deployed. For
LangSmith itself, set `LANGSMITH_API_KEY` in `.env` or your shell, or run
interactively and press Enter at the prompt to sign in with your browser (the
CLI creates a key and writes it to `.env`). Use `LANGSMITH_WORKSPACE_ID` or
`--workspace-id` when your credentials require a workspace selection.
