Monadic Context Engineering (MCE) is a principled architecture for AI agent orchestration that treats workflows as composable computations in a shared context. It formalizes how state, errors, and side effects propagate through agent steps, using the algebraic structures of Functors, Applicatives, and Monads.
This repository provides a Python implementation, including:
AgentMonad: sequential, stateful, fallible computation chains.AsyncAgentMonad: async flows with Applicative parallelism viagather.- Pydantic models for structured state and tool calls/results.
MCE models an agent workflow as a single container that carries:
- State (memory/history)
- A value (current step output)
- A success/failure signal
The .then() operator composes steps. If any step fails, the chain short-circuits, preserving the error and state at the point of failure.
src/mce/monads.py:AgentMonadandAsyncAgentMonad.src/mce/models.py: pydantic models and a tool registry.src/mce/steps.py: reference steps from the paper (plan, execute, synthesize, format).src/mce/__main__.py: a runnable demo.docs/paper.tex: the research paper.docs/index.html: project page.
uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"Run the demo:
python -m mcefrom mce.steps import run_simple_agent
flow = run_simple_agent("What is a Monad?")
if flow.is_successful:
print(flow.value)
for entry in flow.state.history:
print("-", entry)
else:
print("Failure:", flow.error_info)The default steps are deterministic. To use a live LLM call via OpenRouter:
export OPENROUTER_API_KEY="your-key"
export OPENROUTER_MODEL="x-ai/grok-4.1-fast"from mce.steps import run_openrouter_agent
flow = run_openrouter_agent("What is a Monad?")
if flow.is_successful:
print(flow.value)
else:
print("Failure:", flow.error_info)Optional environment variables:
OPENROUTER_BASE_URL(default:https://openrouter.ai/api/v1)OPENROUTER_REFERER(setsHTTP-Referer)OPENROUTER_TITLE(setsX-Title)OPENROUTER_TIMEOUT_S(default:30)
- Type checking:
pyright - Linting:
ruff - Tests:
pytest
pyright
ruff check src tests
pytest- The implementation follows the conceptual design in the paper, including the
AgentMonadandAsyncAgentMonadAPIs. - The default example steps are deterministic and self-contained; use OpenRouter for live LLM calls.