Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Codemode

Secure code execution for multi-agent AI systems

License: MIT Python 3.11-3.13 Code style: black

Codemode enables AI agents to dynamically generate and execute code to orchestrate complex workflows while maintaining production-grade security through isolated execution environments.

Key Features

  • Secure Execution: Code runs in isolated Docker containers with security hardening
  • RPC Bridge: Tools execute in main app with full access, code runs in isolation
  • TLS/mTLS Encryption: End-to-end encryption for all gRPC communications
  • Retry Logic: Automatic retries with exponential backoff for transient failures
  • Correlation IDs: End-to-end request tracing across the distributed system
  • Framework Support: Native CrewAI integration, LangChain and LangGraph coming soon

Quick Start

Installation

pip install opencodemode[crewai]

Basic Usage

from codemode import Codemode
from codemode.config import ClientConfig

# Configure the client
config = ClientConfig(
    executor_url="http://localhost:8001",
    executor_api_key="your-api-key",
)

# Create Codemode instance
codemode = Codemode.from_client_config(config)

# Execute code
result = codemode.execute("result = 2 + 2")
print(result)  # "4"

Environment Variables

Configure via environment variables for production:

export CODEMODE_EXECUTOR_URL="http://executor:8001"
export CODEMODE_EXECUTOR_API_KEY="your-api-key"
from codemode import Codemode

codemode = Codemode.from_env()
result = codemode.execute("result = 2 + 2")

With CrewAI

from crewai import Agent, Task, Crew
from codemode import Codemode

codemode = Codemode.from_env()
code_tool = codemode.as_crewai_tool()

developer = Agent(
    role="Python Developer",
    goal="Write and execute Python code",
    tools=[code_tool],
    backstory="You are an expert Python developer",
)

task = Task(
    description="Calculate the first 10 Fibonacci numbers",
    agent=developer,
    expected_output="List of first 10 Fibonacci numbers",
)

crew = Crew(agents=[developer], tasks=[task])
result = crew.kickoff()

Registering Tools

Register tools that AI-generated code can call back into your main application:

from codemode import Codemode, ComponentRegistry

registry = ComponentRegistry()

# Register a tool instance
registry.register_tool(
    name="weather",
    tool=weather_tool,
    description="Get current weather for a location",
)

codemode = Codemode.from_env(registry=registry)
result = codemode.execute("weather = tools['weather'].run(location='London')")

@tool Decorator

Use the @tool decorator for a concise registration workflow:

from codemode import tool

@tool(name="add", description="Add two numbers")
def add(a: int, b: int) -> int:
    return a + b

@tool(name="weather", description="Get weather")
def get_weather(location: str) -> dict:
    return {"temp": 72, "location": location}

# Register individually
registry.register(add)

# Or auto-discover all decorated tools from a module
import my_tools
registered = registry.discover_tools(my_tools)

Schemas can be attached via the decorator:

from pydantic import BaseModel, Field

class WeatherInput(BaseModel):
    location: str = Field(..., description="City name")

@tool(name="weather", input_schema=WeatherInput)
def get_weather(location: str) -> dict:
    """Get current weather for a location."""
    return {"temp": 72}

Tool Access Filtering

Control which tools each agent can access during execution:

# At execution time, restrict available tools
result = codemode.execute(
    code="data = tools['database'].run(query='SELECT 1')",
    tool_filter=["database", "cache"],
)

# Or create a scoped registry for fine-grained control
scoped = registry.scoped(["weather", "database"])
# scoped.get_tool("weather")  -> works
# scoped.get_tool("admin")    -> raises ComponentNotFoundError

Meta-tools (__list__, __schema__, __search__) are always accessible regardless of filtering.

Meta-Tools

Built-in meta-tools allow executed code to discover available tools at runtime:

Tool Description
__list__ List all available tools with descriptions, async status, and schema availability
__schema__ Get input/output schema for a specific tool by name
__search__ Search for tools by keyword across names and descriptions

Meta-tools are auto-registered when you create a ComponentRegistry. Inside executed code:

# List all tools
all_tools = tools['__list__'].run()

# Get schema for a specific tool
schema = tools['__schema__'].run(name="weather")

# Search for tools by keyword
matches = tools['__search__'].run(query="database")

Architecture

+------------------+        gRPC/HTTP         +------------------+
|                  | -----------------------> |                  |
|   Main App       |    Execute Code          |   Executor       |
|   (Client)       | <----------------------- |   Sidecar        |
|                  |    Tool Callbacks        |   (Docker)       |
+------------------+                          +------------------+
  1. AI agent generates Python code
  2. Code executes in isolated executor (no network, read-only FS)
  3. When code calls tools['database'].run(), gRPC callback to main app
  4. Main app executes real tool with full access
  5. Result returned to executor, code continues

Documentation

Full documentation is available in the docs/ directory:

Docker Setup

# Initialize project
codemode init

# Build executor image
codemode docker build

# Start executor container
codemode docker start

# Verify status
codemode docker status

Additional Docker Commands

# Generate .env file from codemode.yaml (for docker-compose)
codemode docker env --config codemode.yaml --output .env

# Export Docker assets for custom deployment
codemode docker assets --dest ./deploy

# Start with custom configuration
codemode docker start --config custom.yaml --port 8001

# Remove executor container
codemode docker remove

Docker Compose

For multi-container setups:

# Generate .env from your config
codemode docker env --output .env

# Start with docker-compose
docker-compose --env-file .env -f docker_sidecar/docker-compose.yml up -d

See Deployment Guide for detailed Docker instructions.

Security

Codemode implements defense-in-depth security:

  • Container Isolation: Separate container with no external network access
  • Import Blocking: Dangerous modules blocked before execution
  • TLS Encryption: Optional end-to-end encryption with mTLS support
  • Filesystem Protection: Read-only root filesystem
  • Resource Limits: CPU, memory, and process limits
  • Code Validation: Pattern matching for dangerous code

See Security Model for details.

Contributing

We welcome contributions! Here's the workflow:

  1. Fork the repository
  2. Create a feature branch from develop (git checkout -b feature/amazing-feature develop)
  3. Make your changes and commit (git commit -m 'Add amazing feature')
  4. Push to your fork (git push origin feature/amazing-feature)
  5. Open a Pull Request against develop

Branch Strategy

  • develop - Active development branch (submit PRs here)
  • main - Stable releases
  • release-test - Triggers Test PyPI publish
  • release - Triggers PyPI publish

PRs are merged: feature branch -> develop -> main -> release-test -> release

Development Setup

# Clone and setup
git clone https://github.com/mldlwizard/code_mode.git
cd code_mode
git checkout develop
uv sync --extra dev

# Run tests
make test

# Run linting
make lint

# Run E2E tests (requires Docker)
make e2e

See Development Guide for details.

License

MIT License - see LICENSE for details.

Support

Metadata

Release files for opencodemode 0.2.4b12

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for opencodemode 0.2.4b12
File Size Uploaded Provenance Actions
opencodemode-0.2.4b12.tar.gz 494.3 kB Without provenance Details for opencodemode-0.2.4b12.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for opencodemode 0.2.4b12
File Interpreter ABI Platform Actions
opencodemode-0.2.4b12-py3-none-any.whl Python 3 none any Details for opencodemode-0.2.4b12-py3-none-any.whl

Total release size: 607.0 kB

Release files / opencodemode-0.2.4b12.tar.gz

Download URL opencodemode-0.2.4b12.tar.gz
Size 494.3 kB
Tags Source
SHA-256 checksum
How to use checksums
e69c68cea7631287ad8283bcd22c75cfa46a3832ba305313784bf6910fb06e6e
BLAKE2b-256 checksum
How to use checksums
bea2c1ad977c8c50e27f8843399ae4fdbaa24c4e1377d83b2759b5197b3fe494
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.15

Release files / opencodemode-0.2.4b12-py3-none-any.whl

Download URL opencodemode-0.2.4b12-py3-none-any.whl
Size 112.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e55af680005af229463057b336f6f976631ebc8e9518edfe8da505d2deb3c3ee
BLAKE2b-256 checksum
How to use checksums
2f942260158cb3cd9f0e3fd0a7b9641c7dff96f901da6370a7feba05d163f029
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.15

Security for opencodemode 0.2.4b12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page