Skip to main content

No project description provided

Project description

Datalayer

Become a Sponsor

๐Ÿ”ง MCP Codemode

PyPI - Version

Code Mode for MCP Tools: Programmatically call and compose MCP tools through code execution instead of individual LLM tool calls.

Overview

MCP Codemode enables a "Code Mode" pattern where AI agents write Python code that orchestrates multiple MCP tool calls, rather than making individual tool calls through LLM inference. This approach is:

  • More efficient: Reduce LLM calls for multi-step operations
  • More reliable: Use try/except for robust error handling
  • More powerful: Parallel execution with asyncio, loops, conditionals
  • More composable: Save reusable patterns as skills

Configuration highlights

  • Direct tool calls: allow_direct_tool_calls (default: false). When false, call_tool is hidden and all execution flows through execute_code.
  • Tool listing filters: list_tool_names accepts server, keywords, and limit for fast, filtered discovery.
  • Search rerank hook: Provide an optional tool_reranker callable to reorder search results before they are returned (e.g., LLM-based rerankers). Falls back to registry order when not provided.
  • Execution language: execute_code runs Python inside the configured sandbox; import bindings from generated.servers.<server_name>.
  • Safety cap: max_tool_calls can limit the number of tool invocations per execute_code run.
  • Tool examples: tool discovery and details include output_schema and input_examples to improve parameter accuracy.
  • Deferred tools: tools may be marked defer_loading by servers. list_tool_names excludes them by default; search_tools includes them unless include_deferred=false.

Installation

```bash pip install mcp-codemode ```

Quick Start

```python from mcp_codemode import ToolRegistry, CodeModeExecutor, MCPServerConfig

Set up registry with MCP servers

registry = ToolRegistry() registry.add_server(MCPServerConfig( name="filesystem", transport="stdio", command="npx", args=["-y", "@anthropic/mcp-server-filesystem", "/tmp"] )) await registry.discover_all()

Execute code that composes tools

async with CodeModeExecutor(registry) as executor: result = await executor.execute(""" from generated.servers.filesystem import read_file, write_file

    # Read multiple files
    content1 = await read_file({"path": "/tmp/file1.txt"})
    content2 = await read_file({"path": "/tmp/file2.txt"})
    
    # Process and combine
    combined = content1 + "\\n---\\n" + content2
    
    # Write result
    await write_file({"path": "/tmp/combined.txt", "content": combined})
""")

```

Features

Progressive Tool Discovery

Use the Tool Search Tool to discover relevant tools without loading all definitions upfront:

```python

Search for tools matching a description (includes deferred tools)

result = await registry.search_tools("file operations", limit=10, include_deferred=True)

for tool in result.tools: print(f"{tool.name}: {tool.description}")

Fast listing (deferred tools excluded by default)

names = registry.list_tool_names(limit=50) ```

Code-Based Tool Composition

Execute Python code in an isolated sandbox with auto-generated tool bindings:

```python async with CodeModeExecutor(registry) as executor: execution = await executor.execute(""" import asyncio from generated.servers.filesystem import ls, read_file

    # List all files
    files = await ls({"path": "/data"})
    
    # Read all files in parallel
    contents = await asyncio.gather(*[
        read_file({"path": f}) for f in files
    ])
""", timeout=30.0)

Standard outputs are available on the execution object

print(execution.stdout) print(execution.stderr) print(execution.text) ```

Skills (Reusable Compositions)

Skills are Python files that compose tools into reusable operations. This allows agents to evolve their own toolbox by saving useful code patterns.

Creating Skills as Code Files

The primary pattern is skills as Python files in a skills/ directory:

# skills/batch_process.py
"""Process all files in a directory."""

async def batch_process(input_dir: str, output_dir: str) -> dict:
    """Process all files in a directory.
    
    Args:
        input_dir: Input directory path.
        output_dir: Output directory path.
    
    Returns:
        Processing statistics.
    """
    from generated.servers.filesystem import list_directory, read_file, write_file

## Examples

See the runnable examples in [examples/README.md](examples/README.md).

```bash
python examples/codemode_example.py
python examples/codemode_patterns_example.py
entries = await list_directory({"path": input_dir})
processed = 0

for entry in entries.get("entries", []):
    content = await read_file({"path": f"{input_dir}/{entry}"})
    # Process content...
    await write_file({"path": f"{output_dir}/{entry}", "content": content.upper()})
    processed += 1

return {"processed": processed}

#### Using Skills in Executed Code

Skills are imported and called like any Python module:

```python
# In executed code
from skills.batch_process import batch_process

result = await batch_process("/data/input", "/data/output")
print(f"Processed {result['processed']} files")

Composing Skills

Skills can import and use other skills:

# skills/analyze_and_report.py
"""Analyze data and generate a report."""

async def analyze_and_report(data_dir: str) -> dict:
    from skills.batch_process import batch_process
    from skills.generate_report import generate_report
    
    # First process the files
    process_result = await batch_process(data_dir, f"{data_dir}/processed")
    
    # Then generate a report
    report = await generate_report(f"{data_dir}/processed")
    
    return {"processed": process_result["processed"], "report": report}

Managing Skills

from mcp_codemode.skills import SkillDirectory, setup_skills_directory

# Initialize skills directory
skills = setup_skills_directory("./workspace/skills")

# List available skills
for skill in skills.list():
    print(f"{skill.name}: {skill.description}")

# Search for relevant skills
matches = skills.search("data processing")

# Create a new skill programmatically
skills.create(
    name="my_skill",
    code='async def my_skill(x: str) -> str: return x.upper()',
    description="Transform text to uppercase",
)

MCP Server

Expose Code Mode capabilities as an MCP server:

```python from mcp_codemode import codemode_server, configure_server

configure_server() codemode_server.run() ```

Tools exposed:

  • `search_tools` - Progressive tool discovery
  • `execute_code` - Run code that composes tools
  • `call_tool` - Direct tool invocation
  • `save_skill` / `run_skill` - Skill management

Key Concepts

Tool Discovery

Instead of loading all tool definitions upfront (which can overwhelm context), use the Tool Search Tool pattern for progressive discovery based on the task at hand.

Tool Composition

Compose tools through code instead of reading all data into LLM context. This is faster, more reliable (no text reproduction errors), and more efficient.

Control Flow

Code allows models to implement complex control flow: loops, conditionals, waiting patterns, and parallel execution without burning through context with repeated tool calls.

State Persistence

When running in a sandbox (like mcp-codemode), state can persist on disk. Skills themselves can be saved and composed into increasingly powerful tools.

Architecture

``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ MCP Codemode โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ Tool Registry โ”‚ โ”‚ Code Executorโ”‚ โ”‚ Skills โ”‚ โ”‚ โ”‚ โ”‚ - Discovery โ”‚ โ”‚ - Sandbox โ”‚ โ”‚ - Save โ”‚ โ”‚ โ”‚ โ”‚ - Search โ”‚ โ”‚ - Bindings โ”‚ โ”‚ - Load โ”‚ โ”‚ โ”‚ โ”‚ - Cache โ”‚ โ”‚ - Execute โ”‚ โ”‚ - Execute โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ mcp-codemode โ”‚ โ”‚ (Isolated execution environment) โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ```

References

License

BSD 3-Clause License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_codemode-0.0.4-py3-none-any.whl (39.8 kB view details)

Uploaded Python 3

File details

Details for the file mcp_codemode-0.0.4-py3-none-any.whl.

File metadata

  • Download URL: mcp_codemode-0.0.4-py3-none-any.whl
  • Upload date:
  • Size: 39.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for mcp_codemode-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 c38bb524d55eed22d92dd3e158381ba1a5c27fae1282a2c755680f0d97ad53f2
MD5 4d7c4814fc2c8846b5e9e5e78002f5f9
BLAKE2b-256 d144d9228089bfa8fa048876c575e2a64c6f2d3970d266f710aa2df4fbfd95d9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page