Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions python/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ python/

### Experimental
- [lab](packages/lab/AGENTS.md) - Experimental features
- [monty](packages/monty/AGENTS.md) - Monty-backed CodeAct integrations (alpha)
1 change: 1 addition & 0 deletions python/PACKAGE_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Status is grouped into these buckets:
| `agent-framework-hyperlight` | `python/packages/hyperlight` | `beta` |
| `agent-framework-lab` | `python/packages/lab` | `beta` |
| `agent-framework-mem0` | `python/packages/mem0` | `beta` |
| `agent-framework-monty` | `python/packages/monty` | `alpha` |
| `agent-framework-ollama` | `python/packages/ollama` | `beta` |
| `agent-framework-openai` | `python/packages/openai` | `released` |
| `agent-framework-orchestrations` | `python/packages/orchestrations` | `beta` |
Expand Down
78 changes: 78 additions & 0 deletions python/packages/monty/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Monty Package (agent-framework-monty)

Monty-backed CodeAct integrations for the Microsoft Agent Framework.

> [!NOTE]
> **Alpha package.** Not part of `agent-framework[all]` yet. Install explicitly
> with `pip install agent-framework-monty --pre`.

## Core Classes

- **`MontyCodeActProvider`** — `ContextProvider` that injects a run-scoped
`execute_code` tool plus dynamic CodeAct instructions. Mirrors the
`HyperlightCodeActProvider` API for the parts that apply to a non-sandboxed
Python interpreter.
- **`MontyExecuteCodeTool`** — `FunctionTool` that wraps the Monty interpreter.
Use directly for mixed-tool agents or manual static wiring. Mirrors
`HyperlightExecuteCodeTool`.

## Public API

```python
from agent_framework_monty import (
FileMount,
FileMountInput,
MontyCodeActProvider,
MontyExecuteCodeTool,
MountMode,
)
```

`MontyCodeActProvider` and `MontyExecuteCodeTool` both accept:
- `tools` — host tool callables / `FunctionTool`s
- `approval_mode` — `"never_require"` (default) or `"always_require"`
- `workspace_root` — host directory auto-mounted at `/input`
(mirrors `HyperlightCodeActProvider.workspace_root`)
- `file_mounts` — sequence of `FileMountInput` (str shorthand,
`(host_path, mount_path)` tuple, or `FileMount`)
- `resource_limits` — Monty `ResourceLimits` TypedDict

Tool-management methods on both classes: `add_tools`, `get_tools`,
`remove_tool`, `clear_tools`. Mount-management methods: `add_file_mounts`,
`get_file_mounts`, `remove_file_mount`, `clear_file_mounts`.

`MontyExecuteCodeTool` additionally exposes:
- `build_instructions(*, tools_visible_to_model: bool) -> str`
- `create_run_tool() -> MontyExecuteCodeTool`
- `build_serializable_state() -> dict[str, Any]`
- `workspace_root`, `resource_limits` properties

## Architecture

- **`_types.py`** — `FileMount`, `FileMountInput`, `MountMode` (public).
- **`_provider.py`** — `MontyCodeActProvider` (thin wrapper around the tool).
- **`_execute_code_tool.py`** — `MontyExecuteCodeTool` plus tool / mount
normalization, approval helpers, dynamic `description`/`instructions`
builders, and the post-execution file-capture flow that surfaces files
written to `read-write` mounts as `Content.from_data` items.
- **`_monty_bridge.py`** — `InlineCodeBridge` and `generate_type_stubs`,
adapted from the reference Monty CodeAct repo. Pauses on `FunctionSnapshot`
to dispatch host calls, then resumes; supports direct typed tool calls,
the `call_tool` fallback, `asyncio.gather` fan-out, and forwards
``mount`` / ``limits`` to `Monty(...).start(...)`.
- **`_instructions.py`** — dynamic instruction / tool-description builders
(include filesystem capability summaries when mounts are configured).

## Not implemented (yet)

| Capability | Monty primitive | Status |
|------------|-----------------|--------|
| Custom virtual filesystem | `OSAccess` subclass passed to `Monty(...).start(os=...)` | Not exposed. Strictly more general than file mounts; useful when you want a fully synthetic FS. |
| Outbound URL allow-list | No Monty primitive — expose `fetch_url` as a host tool with the allow-list check in your tool function. | Not exposed in this package; users add it as a regular tool. |

## Out of scope (for now)

- **Durable execution** — the reference Monty CodeAct repo also offers a
Durable-Functions-backed mode (`DurableCodeBridge`, `register_durable_codeact`,
`wait_for_external_event`, per-tool approval via external events). That is
intentionally not in this package yet.
21 changes: 21 additions & 0 deletions python/packages/monty/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
179 changes: 179 additions & 0 deletions python/packages/monty/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# agent-framework-monty

Monty-backed CodeAct integrations for Microsoft Agent Framework.

> [!WARNING]
> This package is in **alpha**. APIs may change without notice. It is not part of
> `agent-framework[all]` yet; install it explicitly with `--pre`.

## Installation

```bash
pip install agent-framework-monty --pre
```

The package depends on [`pydantic-monty`](https://github.com/pydantic/monty), a
Rust-based Python interpreter, so it runs on Linux, macOS, and Windows wherever
Monty wheels are published — no hypervisor or WASM backend required.

## Quick start

### Context provider (recommended)

Use `MontyCodeActProvider` to automatically inject the `execute_code` tool and
CodeAct instructions into every agent run. Tools registered on the provider are
available inside the Monty interpreter as **typed async functions** (e.g.
`await compute(operation="add", a=1, b=2)`), and as a fallback through
`call_tool(...)`.

```python
from agent_framework import Agent, tool
from agent_framework_monty import MontyCodeActProvider


@tool
def compute(operation: str, a: float, b: float) -> float:
"""Perform a math operation."""
ops = {"add": a + b, "subtract": a - b, "multiply": a * b, "divide": a / b}
return ops[operation]


codeact = MontyCodeActProvider(
tools=[compute],
approval_mode="never_require",
)

agent = Agent(
client=client,
name="CodeActAgent",
instructions="You are a helpful assistant.",
context_providers=[codeact],
)

result = await agent.run("Multiply 6 by 7 using execute_code.")
```

### Standalone tool

Use `MontyExecuteCodeTool` directly when you want full control over how the
tool is added to the agent (e.g. when mixing sandbox tools with direct-only
tools on the same agent).

```python
from agent_framework import Agent, tool
from agent_framework_monty import MontyExecuteCodeTool


@tool
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email (direct-only, not available inside the sandbox)."""
return f"Email sent to {to}"


execute_code = MontyExecuteCodeTool(
tools=[compute],
approval_mode="never_require",
)

agent = Agent(
client=client,
name="MixedToolsAgent",
instructions="You are a helpful assistant.",
tools=[send_email, execute_code],
)
```

### Manual static wiring

For fixed configurations where provider lifecycle overhead is unnecessary,
build the CodeAct instructions once and pass them to the agent at construction
time:

```python
execute_code = MontyExecuteCodeTool(
tools=[compute],
approval_mode="never_require",
)

codeact_instructions = execute_code.build_instructions(tools_visible_to_model=False)

agent = Agent(
client=client,
name="StaticWiringAgent",
instructions=f"You are a helpful assistant.\n\n{codeact_instructions}",
tools=[execute_code],
)
```

### File mounts and resource limits

Mount host directories into the sandbox and cap execution resources:

```python
from agent_framework_monty import FileMount, MontyCodeActProvider

codeact = MontyCodeActProvider(
tools=[compute],
workspace_root="/host/workspace", # auto-mounted at /input (read-write)
file_mounts=[
"/host/data", # shorthand: same path on both sides
("/host/models", "/sandbox/models"), # explicit (host, mount_path)
FileMount( # full control
host_path="/host/cache",
mount_path="/sandbox/cache",
mode="overlay", # "read-only" | "read-write" | "overlay"
write_bytes_limit=10 * 1024 * 1024,
),
],
resource_limits={ # Monty ResourceLimits TypedDict
"max_duration_secs": 5.0,
"max_memory": 64 * 1024 * 1024,
},
)
```

- **`workspace_root`** mirrors the Hyperlight default: the directory is mounted
at `/input` in `read-write` mode.
- **`file_mounts`** accepts a string shorthand, a `(host_path, mount_path)`
tuple, or a `FileMount` named tuple (with optional `mode` and
`write_bytes_limit`).
- Files written by the sandbox to any **`read-write`** mount are scanned
after each `execute_code` call and returned as `Content.from_data(...)`
attachments (with a `path` annotation in `additional_properties`),
mirroring Hyperlight's `/output` flow.
- `overlay` mounts buffer writes in memory (nothing leaks to the host and
nothing is captured). `read-only` mounts reject writes.
- **`resource_limits`** is forwarded straight to Monty's
[`ResourceLimits`](https://github.com/pydantic/monty) TypedDict
(`max_allocations`, `max_duration_secs`, `max_memory`, `gc_interval`,
`max_recursion_depth`).

## DSL inside `execute_code`

The model generates Python code that runs inside Monty's Rust-based interpreter.
Available primitives:

| Primitive | Behavior |
|-----------|----------|
| `await tool_name(**kwargs)` | Direct typed call to a registered host tool. Argument types are checked before execution. |
| `await call_tool("name", **kwargs)` | Generic fallback that dispatches by tool name. Not type-checked. |
| `asyncio.gather(...)` | Fans out concurrent tool calls. |
| `print(...)` | Captured and surfaced as text in the tool result. |

## Notes

- `MontyCodeActProvider` and `MontyExecuteCodeTool` mirror the API surface of
the `agent-framework-hyperlight` counterparts where the underlying runtime
supports it.
- Monty interprets a **subset** of Python (a Rust-based interpreter). Most
control flow, common stdlib modules (`sys`, `os`, `typing`, `asyncio`, `re`,
`datetime`, `json`), and async functions are supported, but exotic features
may not be available. OS-level access (filesystem, network, subprocess) is
rejected with `PermissionError` **by default**; mount host directories with
`workspace_root` / `file_mounts` to grant scoped filesystem access.
- Code is type-checked against tool signatures via
[ty](https://docs.astral.sh/ty/) before execution, so wrong argument types
surface as a clear error before any host tool runs.
- The alpha package is **not** part of `agent-framework[all]` yet, so it must
be installed explicitly. Once promoted to beta it will be reachable via the
lazy-loading namespace `agent_framework.monty`.
23 changes: 23 additions & 0 deletions python/packages/monty/agent_framework_monty/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Copyright (c) Microsoft. All rights reserved.

from __future__ import annotations

import importlib.metadata

from ._execute_code_tool import MontyExecuteCodeTool
from ._provider import MontyCodeActProvider
from ._types import FileMount, FileMountInput, MountMode

try:
__version__ = importlib.metadata.version(__name__)
except importlib.metadata.PackageNotFoundError:
__version__ = "0.0.0"

__all__ = [
"FileMount",
"FileMountInput",
"MontyCodeActProvider",
"MontyExecuteCodeTool",
"MountMode",
"__version__",
]
Loading
Loading