Skip to main content

Graphton

CI Python 3.11+ License: Apache-2.0

Declarative agent creation framework for LangGraph

Graphton eliminates boilerplate when creating LangGraph agents with MCP tools. Create production-ready agents in 3-10 lines instead of 100+.

Features

  • Declarative Agent Creation: Minimal boilerplate - just specify model and behavior
  • Automatic Prompt Enhancement: Agents automatically understand available capabilities (planning, file system, MCP tools)
  • Universal MCP Authentication: Support for any MCP server configuration with both static and dynamic authentication modes
  • Intelligent Loop Detection: Automatically detects and prevents infinite loops in autonomous agents
  • Production Ready: Works in both local and remote LangGraph deployments
  • Type-Safe Configuration: Pydantic validation with helpful error messages
  • IDE Support: Full autocomplete and type hints for better developer experience

Quick Start

Installation

pip install graphton

Simple Agent

Create a basic agent in just 3 lines:

from graphton import create_deep_agent

SYSTEM_PROMPT = """You are a helpful assistant that answers questions concisely.
When answering questions:
- Be direct and to the point
- Provide accurate information
- If you're not sure, say so
"""

# Create agent with just model and prompt
agent = create_deep_agent(
    model="claude-sonnet-4.5",
    system_prompt=SYSTEM_PROMPT,
)

# Invoke the agent
result = agent.invoke({
    "messages": [{"role": "user", "content": "What is the capital of France?"}]
})

Agent with MCP Tools

Integrate MCP tools with dynamic per-user authentication:

from graphton import create_deep_agent
import os

# Agent with dynamic MCP authentication
agent = create_deep_agent(
    model="claude-sonnet-4.5",
    system_prompt="You are a Planton assistant helping users manage cloud resources.",
    
    # MCP integration with template variables
    mcp_servers={
        "planton": {
            "transport": "streamable_http",
            "url": "https://mcp.planton.ai/",
            "headers": {
                "Authorization": "Bearer {{USER_TOKEN}}"  # Substituted at runtime
            }
        }
    },
    mcp_tools={
        "planton": [
            "list_organizations",
            "search_cloud_resources",
            "create_cloud_resource",
        ]
    },
    
    # Optional parameters
    recursion_limit=150,
    temperature=0.3,
)

# Invoke with user-specific token
result = agent.invoke(
    {"messages": [{"role": "user", "content": "List my organizations"}]},
    config={
        "configurable": {
            "USER_TOKEN": os.getenv("PLANTON_API_KEY")
        }
    }
)

Static MCP Configuration

For shared credentials, use static configuration (tools loaded once at creation time):

agent = create_deep_agent(
    model="claude-sonnet-4.5",
    system_prompt="You are an API assistant.",
    
    mcp_servers={
        "public-api": {
            "transport": "http",
            "url": "https://api.example.com/mcp",
            "headers": {
                "X-API-Key": "hardcoded-key-123"  # No templates = static
            }
        }
    },
    mcp_tools={
        "public-api": ["search", "fetch"]
    }
)

# Invoke without auth config - credentials already in config
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Search for Python"}]}
)

Agent with Sub-agents

Delegate complex tasks to specialized sub-agents with isolated context:

from graphton import create_deep_agent

agent = create_deep_agent(
    model="claude-sonnet-4.5",
    system_prompt="You are a research coordinator that delegates specialized tasks.",
    
    # Define specialized sub-agents
    subagents=[
        {
            "name": "deep-researcher",
            "description": "Conducts thorough research on complex topics with comprehensive analysis",
            "system_prompt": "You are a research specialist. Conduct thorough research, cite sources, and provide comprehensive analysis.",
        },
        {
            "name": "code-reviewer",
            "description": "Reviews code for quality, security, and best practices",
            "system_prompt": "You are a code review expert. Analyze code for bugs, security issues, and improvement opportunities.",
        }
    ],
    
    # Include general-purpose sub-agent for other tasks
    general_purpose_agent=True,
)

# The agent can now delegate tasks to sub-agents
result = agent.invoke({
    "messages": [{"role": "user", "content": "Research quantum computing and review the attached code"}]
})

When to use sub-agents:

  • Complex multi-step tasks that can be delegated
  • Independent parallel tasks
  • Tasks requiring focused reasoning without context bloat
  • Specialized domains (research, code review, data analysis)

Benefits:

  • Context isolation: Each sub-agent has its own context window
  • Token efficiency: Main agent gets concise summaries, not full task history
  • Parallel execution: Launch multiple sub-agents simultaneously
  • Specialization: Different sub-agents with domain-specific tools

Automatic Prompt Enhancement

Graphton automatically enhances your instructions with awareness of Deep Agents capabilities. This ensures agents understand what tools they have and when to use them.

What Gets Enhanced

When you provide simple instructions like:

agent = create_deep_agent(
    model="claude-sonnet-4.5",
    system_prompt="You are a helpful research assistant.",
)

Graphton automatically adds context about:

  • Planning System: For breaking down complex multi-step tasks
  • File System: For storing and managing information across operations
  • MCP Tools: When configured, awareness of domain-specific capabilities

Why This Matters

Deep Agents come with powerful built-in tools (planning, file system, subagents), but agents won't use them effectively unless they know they exist. Graphton bridges this gap by automatically informing agents about available capabilities.

Control and Flexibility

  • Automatic by default: Enhancement happens automatically for all agents
  • Redundancy is fine: If your instructions already mention planning or file system, some overlap will occur. This is intentional - LLMs handle redundancy gracefully, and reinforcement is better than missing critical context
  • Can be disabled: Use auto_enhance_prompt=False to pass instructions as-is
# Disable enhancement if you've already included all context
agent = create_deep_agent(
    model="claude-sonnet-4.5",
    system_prompt="Detailed instructions with all tool context...",
    auto_enhance_prompt=False,  # Use prompt as-is
)

Documentation

  • Configuration Guide - Complete reference for all configuration options
  • API Documentation - Full API reference
  • Examples - More usage examples including:
    • simple_agent.py - Basic agent without MCP
    • mcp_agent.py - Dynamic MCP authentication
    • static_mcp_agent.py - Static MCP configuration
    • multi_auth_agent.py - Multiple servers with mixed authentication

Universal MCP Authentication

Graphton supports any MCP server configuration format and authentication method through template-based token injection:

Dynamic Mode (with {{VAR}} templates):

  • Templates substituted from config['configurable'] at invocation time
  • Tools loaded per-request with user-specific authentication
  • Use for multi-tenant systems or per-user tokens

Static Mode (no template variables):

  • Tools loaded once at agent creation time
  • Zero runtime overhead
  • Use for hardcoded credentials or public servers

Supported authentication methods:

  • Bearer tokens (OAuth, JWT)
  • API Keys
  • Basic Auth
  • Custom headers
  • Any authentication format supported by your MCP server

Durable Execution & Tool Idempotency

When running Graphton agents through Temporal workflows (as in Stigmer), agents benefit from durable execution - the ability to resume from checkpoints after crashes or failures.

How Crash Recovery Works

  1. LangGraph checkpoints state (messages, tool decisions) to MongoDB after each step
  2. Temporal heartbeats include the thread_id (checkpoint identifier)
  3. On crash/retry, the activity extracts thread_id from heartbeat and resumes from checkpoint
  4. Agent continues from the last saved state instead of restarting

Tool Idempotency Guidelines

While LangGraph checkpointing handles most crash recovery, there's a small window where a tool may execute but the checkpoint hasn't been saved yet. For critical operations, tools should be designed to be idempotent (safe to run multiple times).

Read-only tools (no special handling needed)

These tools are naturally idempotent - re-running them produces the same result:

  • read, ls, glob, grep
  • Database queries (SELECT statements)
  • API GET requests

Create operations (should check for existing resources)

Tools that create resources should check if the resource already exists:

@tool
async def create_pull_request(title: str, branch: str) -> str:
    """Create a PR - checks for existing PR first."""
    # Check if PR already exists
    existing = await github.get_prs(head=branch, state="open")
    if existing:
        return f"PR already exists: {existing[0].url}"
    
    # Create new PR
    pr = await github.create_pr(title=title, branch=branch)
    return f"Created PR: {pr.url}"

External API calls (use API-level idempotency)

Many APIs support idempotency keys to prevent duplicate operations:

@tool
async def charge_payment(amount: float, customer_id: str) -> str:
    """Charge payment with idempotency key."""
    import hashlib
    
    # Generate deterministic idempotency key from operation parameters
    key = hashlib.sha256(f"{customer_id}:{amount}:{context.execution_id}".encode()).hexdigest()
    
    result = await stripe.charges.create(
        amount=int(amount * 100),
        customer=customer_id,
        idempotency_key=key,  # Stripe prevents duplicate charges
    )
    return f"Charged ${amount}: {result.id}"

Destructive operations (usually idempotent)

Most delete operations are naturally idempotent:

  • delete_file - deleting a non-existent file is typically a no-op
  • remove_user - removing a non-existent user returns success

When idempotency is critical

For operations with significant side effects, consider:

  1. Check-before-act: Verify the operation hasn't been done
  2. Idempotency keys: Use API-provided idempotency mechanisms
  3. Transaction IDs: Include execution context in transaction identifiers

Summary

Tool Type Idempotent? Recommendation
Read operations Yes No action needed
Create operations No Check if resource exists first
API calls with idempotency Yes Use idempotency keys
Delete operations Usually Handle "not found" gracefully
Send notifications No Use API idempotency or dedup logic

Requirements

  • Python 3.11 or higher
  • Poetry (for development)

License

Apache-2.0 - See LICENSE for details

Contributing

We welcome contributions! Please see CONTRIBUTING.md for development setup and guidelines.

Metadata

Release files for graphton 1.0.4

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

Source distribution (sdist)

Source distribution for graphton 1.0.4
File Size Uploaded Provenance Actions
graphton-1.0.4.tar.gz 154.0 kB With provenance Details for graphton-1.0.4.tar.gz

Built distribution (wheel)

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

Total release size: 327.6 kB

Release files / graphton-1.0.4.tar.gz

Download URL graphton-1.0.4.tar.gz
Size 154.0 kB
Tags Source
SHA-256 checksum
How to use checksums
dc65413fedd674692cc8486a1fc4b943bf86cd0771bb43389505a65fd79e29de
BLAKE2b-256 checksum
How to use checksums
68844d9bf2863c2aee825f1486c2b218c7ce4f9434ac57870eabd710e0407499
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 18, 2026.

Transparency log

Release files / graphton-1.0.4-py3-none-any.whl

Download URL graphton-1.0.4-py3-none-any.whl
Size 173.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0e6adb5549d065c3992a75f830fe359493000499bd51ccc8e71daa48c127ac67
BLAKE2b-256 checksum
How to use checksums
04fad5baa9ffa5413b90fac9a44fa89eb30106fc27704aa62c934ce405fe7e27
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 18, 2026.

Transparency log

Security for graphton 1.0.4

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for graphton-1.0.4.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 18, 2026.

Transparency log

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