> ## Documentation Index
> Fetch the complete documentation index at: https://datagen.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Mode

> Write Python or TypeScript scripts for bulk workflows and programmatic tool calling

Code mode lets you write local scripts that call MCP tools through the DataGen SDK. Use it when you need batch processing, complex logic, or production-grade automation that goes beyond interactive MCP tool calls.

<Tip>
  **Using Claude Code?** Run `/datagen:code-mode` for guided scripting with tool discovery, durable checkpoint patterns, and large output handling.
</Tip>

## When to Use Code Mode

<CardGroup cols={2}>
  <Card title="Use MCP Tools When" icon="comments">
    * Interactive discovery and debugging
    * Simple one-off operations
    * Learning tool schemas
    * AI agent-assisted work
  </Card>

  <Card title="Use Code Mode When" icon="code">
    * Batch processing (100+ operations)
    * Scheduled jobs and cron tasks
    * CI/CD pipelines
    * Complex data transformations
    * Production applications
  </Card>
</CardGroup>

**Rule of thumb:** fewer than 5 tool calls with small results -- use MCP directly. More than 5 calls, large data, or complex logic -- write a script with the SDK.

***

## Installation

<Tabs>
  <Tab title="Python">
    ```bash theme={null}
    pip install datagen-python-sdk
    ```
  </Tab>

  <Tab title="TypeScript">
    ```bash theme={null}
    npm install @datagen-dev/typescript-sdk
    ```
  </Tab>
</Tabs>

Set your API key:

```bash theme={null}
export DATAGEN_API_KEY="your_api_key_here"
```

***

## Quick Start

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from datagen_sdk import DatagenClient

    client = DatagenClient()

    # Call any MCP tool as a Python function
    result = client.execute_tool(
        "mcp_Linear_list_issues",
        {"filter": {"state": {"name": {"eq": "In Progress"}}}}
    )

    print(f"Found {len(result)} active issues")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { DatagenClient } from '@datagen-dev/typescript-sdk';

    const client = new DatagenClient();

    const result = await client.executeTool(
        "mcp_Linear_list_issues",
        { filter: { state: { name: { eq: "In Progress" } } } }
    );

    console.log(`Found ${result.length} active issues`);
    ```
  </Tab>
</Tabs>

***

## Patterns

### Simple Script

One-off data operations:

```python theme={null}
from datagen_sdk import DatagenClient

client = DatagenClient()

# Fetch leads from database
leads = client.execute_tool("mcp_Supabase_run_sql", {
    "params": {
        "sql": "SELECT * FROM leads WHERE score > 80",
        "projectId": "your-project",
        "databaseName": "your-db"
    }
})

# Create follow-up tasks in Linear
for lead in leads:
    client.execute_tool("mcp_Linear_create_issue", {
        "title": f"Follow up with {lead['company']}",
        "description": f"Contact: {lead['email']}\nScore: {lead['score']}",
        "teamId": "your-team-id"
    })

# Notify team on Slack
client.execute_tool("mcp_Slack_chat_postMessage", {
    "channel": "#sales",
    "text": f"Created {len(leads)} follow-up tasks for high-priority leads"
})
```

### Batch Processing with Error Handling

Process large datasets with retry logic:

```python theme={null}
from datagen_sdk import DatagenClient, DatagenToolError

client = DatagenClient(retries=3, backoff_seconds=1.0)

contacts = [...]  # Your contact list

results = []
errors = []

for contact in contacts:
    try:
        result = client.execute_tool("mcp_Gmail_gmail_send_email", {
            "to": contact["email"],
            "subject": "Welcome!",
            "body": f"Hi {contact['name']}, thanks for signing up!"
        })
        results.append({"email": contact["email"], "status": "sent"})
    except DatagenToolError as e:
        errors.append({"email": contact["email"], "error": str(e)})

print(f"Sent: {len(results)}, Failed: {len(errors)}")
```

### Deploy as Custom Tool

Turn your script into a deployed API endpoint:

```python theme={null}
from datagen_sdk import DatagenClient

client = DatagenClient()

# Deploy your script as a custom tool
deployment = client.deploy_custom_tool(
    name="weekly_lead_enrichment",
    description="Enrich new leads with LinkedIn and web data",
    code=open("enrich.py").read(),
    input_schema={
        "type": "object",
        "properties": {
            "domains": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["domains"]
    },
    output_vars=["enriched_leads", "total"],
    expected_tools=["mcp_LinkedIn_get_company", "mcp_Perplexity_search"],
    mcp_server_names=["LinkedIn", "Perplexity"]
)

print(f"Deployed: {deployment['deployment_uuid']}")

# Run it
result = client.run_custom_tool(
    deployment["deployment_uuid"],
    input_vars={"domains": ["acme.com", "globex.com"]}
)
print(result["output_vars"])
```

***

## Error Handling

```python theme={null}
from datagen_sdk import (
    DatagenClient,
    DatagenAuthError,
    DatagenToolError,
    DatagenHttpError
)

client = DatagenClient(retries=3, backoff_seconds=0.5)

try:
    result = client.execute_tool("mcp_Linear_list_projects", {"limit": 10})
except DatagenAuthError:
    print("Authentication failed - check your API key")
except DatagenToolError as e:
    print(f"Tool execution failed: {e}")
except DatagenHttpError as e:
    print(f"HTTP error: {e}")
```

| Error                    | Description                                                        |
| ------------------------ | ------------------------------------------------------------------ |
| `DatagenAuthError`       | Authentication failed (401/403) -- check API key or MCP connection |
| `DatagenToolError`       | Tool execution failed -- check parameters                          |
| `DatagenHttpError`       | Network or HTTP-level errors                                       |
| `DatagenDeploymentError` | Deployment or custom tool run failed                               |
| `DatagenSecretError`     | Secret management errors                                           |

***

## Full API Reference

For complete method signatures, parameters, and return types, see:

<CardGroup cols={2}>
  <Card title="Python SDK Reference" icon="python" href="/reference/sdk-python">
    Every method, every parameter
  </Card>

  <Card title="TypeScript SDK Reference" icon="js" href="/reference/sdk-typescript">
    Every method, every parameter
  </Card>
</CardGroup>
