Execution Flow

Understanding how tools are executed helps you write better code, debug issues more effectively, and understand what happens when an AI assistant calls your tool. This page explains the complete execution flow from request to response.

The Complete Execution Flow

When an AI assistant calls your tool, a sophisticated process ensures secure, reliable execution. Understanding each step helps you write tools that work correctly and debug issues when they arise.

Step-by-Step Execution Process

  • Request received via MCP protocol - An AI assistant sends a request to call your tool through the MCP (Model Context Protocol). The request includes the tool name and the parameters the AI wants to pass to your tool. This request is received by the MCP server that contains your tool.

  • Tool code is validated - Before execution, the platform validates your tool code to ensure it's safe to run. This validation checks for:

  • Syntax errors (malformed JavaScript) - Security violations (attempts to use blocked features) - Code structure (ensures the execute function exists) If validation fails, the execution stops immediately with a clear error message explaining what's wrong.

- **Sandbox context is created** - A fresh, isolated sandbox environment is created for this execution. This sandbox is completely isolated from other tools, previous executions, and the system. It contains only the APIs and features that are safe to use. Each execution gets its own sandbox, ensuring complete isolation. - **Parameters and config are injected** - The parameters provided by the AI assistant and the workspace secrets (from the config) are injected into the sandbox. Your tool's execute function receives these as the `params` and `config` parameters. This is the only way data enters the sandbox - there's no other way to pass data in. - **Code executes in sandbox** - Your tool's code runs in the isolated sandbox. It can use the available APIs (fetch, console, JSON, etc.) but cannot access anything outside the sandbox. The execution is monitored for timeouts, memory usage, and errors. If your code tries to use a blocked feature, the execution stops immediately. - **Result is captured and returned** - When your code completes (or times out), the return value is captured. If your code returns a value, that's used. If it throws an error, the error is caught and formatted. The result (or error) is then sent back to the AI assistant through the MCP protocol. After the result is captured, the sandbox is destroyed, ensuring no data persists between executions. ### Visual Flow Diagram

Here's how the execution flow looks:

AI Assistant Request ↓ MCP Server Receives Request ↓ Tool Code Validation ↓ (if valid) Sandbox Creation ↓ Parameters & Config Injection ↓ Code Execution (in sandbox) ↓ Result Capture ↓ Response to AI Assistant ↓ Sandbox Destruction

What Happens in Parallel

Multiple executions can happen simultaneously:

  • Each execution gets its own isolated sandbox

  • Executions don't interfere with each other

  • Resource limits apply per execution, not globally

  • One slow execution doesn't block others

This means your tool can handle multiple concurrent requests without issues, as long as each individual execution stays within its limits.

Understanding Parameter Passing

Parameters are the primary way data flows from the AI assistant into your tool. Understanding how parameters work helps you write tools that receive and use data correctly.

How Parameters Are Passed

When an AI assistant calls your tool, it provides parameters as a JavaScript object. This object is passed to your tool's execute function as the first parameter:

Parameter Structure

The params object structure matches the parameter schema you defined for your tool. For example, if your tool has these parameters:

  • city (string, required)

  • units (string, optional, default: "celsius")

Then params might look like:

Or if units wasn't provided:

Best Practices for Parameter Handling

  • Always validate parameters - Check that required parameters exist and are the correct type

  • Use destructuring - Extract parameters you need at the start of your function

  • Handle optional parameters - Check if optional parameters exist before using them

  • Provide defaults - Use default values for optional parameters when appropriate

  • Return clear errors - If parameters are invalid, return a clear error message

Example: Comprehensive Parameter Handling

Understanding Config/Secrets Access

Workspace secrets are passed to your tool through the config parameter. This is the secure way to access API keys, passwords, and other sensitive configuration values.

How Config Works

The config object contains all the secrets you've stored in your workspace. Each secret is accessible as a property of the config object:

Config Object Structure

The config object is a simple key-value mapping where keys are secret names and values are secret values. For example, if your workspace has these secrets:

  • API_KEY = "abc123"

  • API_BASE_URL = "https://api.example.com"

Then config will be:

Best Practices for Config Access

  • Always check if secrets exist - Before using a secret, verify it exists in config

  • Provide clear error messages - If a required secret is missing, return a helpful error

  • Never log secrets - Don't use console.log with secret values

  • Use descriptive secret names - Name your secrets clearly so it's obvious what they're for

Example: Safe Config Access

Security Notes

  • Secrets are encrypted at rest and only decrypted when injected into the sandbox

  • Secrets are never exposed in logs, error messages, or responses

  • Each execution gets a fresh copy of secrets - they're not stored in the sandbox

  • Secrets are workspace-scoped - tools in one workspace can't access secrets from another

Understanding Return Values

Your tool must return a value in a specific format so the AI assistant can understand and use the result. Understanding this format is crucial for building tools that work correctly.

The Standard Return Format

All tools should return an object with this structure:

Success Response

When your tool completes successfully, return:

The data property can contain any structure - objects, arrays, primitives, whatever makes sense for your tool. The AI assistant will receive this data and can use it to answer the user's question or perform further actions.

Error Response

When your tool encounters an error, return:

The error message should be clear and helpful. It will be shown to the AI assistant, which can then explain the error to the user or try an alternative approach.

Why This Format Matters

The standardized return format ensures:

  • Consistency - AI assistants always know how to interpret tool responses

  • Error handling - Clear distinction between success and failure

  • Flexibility - The data property can contain any structure

  • Clarity - Easy to understand whether the tool succeeded or failed

Example: Complete Return Handling

Understanding Error Handling

Errors can occur at various stages of execution. Understanding how errors are handled helps you write robust tools and debug issues effectively.

Types of Errors

Errors can occur at different stages:

1. Validation Errors

When: Before execution starts, during code validation

Causes: - Syntax errors in your JavaScript code - Attempts to use blocked features (detected during static analysis) - Missing execute function - Invalid code structure

What happens: Execution never starts. You receive a validation error immediately with details about what's wrong.

Example: "SyntaxError: Unexpected token" or "Blocked feature detected: require() is not allowed"

2. Runtime Errors

When: During code execution

Causes: - Reference errors (accessing undefined variables) - Type errors (calling methods on wrong types) - API errors (failed HTTP requests) - Logic errors (your code throws an exception)

What happens: If your code doesn't catch the error, it's automatically caught by the platform. The error is formatted and returned as a failure response.

Example: "TypeError: Cannot read property 'name' of undefined" or "Failed to fetch: Network error"

3. Timeout Errors

When: After 30 seconds of execution

Causes: - Your code takes too long to complete - Infinite loops or very slow operations - Slow API responses

What happens: Execution is automatically terminated. A timeout error is returned.

Example: "Execution timeout: Tool exceeded maximum execution time of 30 seconds"

4. Resource Limit Errors

When: During execution, if limits are exceeded

Causes: - Memory usage exceeds limits - CPU usage exceeds limits

What happens: Execution is terminated with a resource limit error.

Example: "Memory limit exceeded" or "CPU limit exceeded"

Error Response Format

All errors are returned in a consistent format:

Best Practices for Error Handling

  • Handle errors in your code - Use try-catch blocks to catch and handle errors gracefully

  • Return clear error messages - When returning errors, provide messages that explain what went wrong

  • Validate inputs early - Check parameters and secrets before doing expensive operations

  • Test error scenarios - Test what happens when things go wrong, not just when they work

  • Don't expose sensitive information - Error messages should never include secrets or sensitive data

Example: Comprehensive Error Handling

Execution Logging and Monitoring

Every tool execution is logged for debugging and monitoring purposes. Understanding what's logged helps you debug issues and monitor your tools' performance.

What Gets Logged

  • Execution start time - When the execution began

  • Parameters received - The parameters passed to your tool (sensitive values may be sanitized)

  • Console output - All console.log, console.error, etc. output from your code

  • Execution duration - How long the execution took

  • Result or error - What your tool returned or what error occurred

  • Resource usage - Memory and CPU usage during execution

Accessing Logs

You can view execution logs in the platform dashboard:

  • Navigate to your tool

  • View the execution history

  • See detailed logs for each execution

  • Filter by success/failure, date, or other criteria

Logs are invaluable for debugging - they show exactly what happened during execution, what parameters were received, what console output was produced, and what the result was.

Summary: Key Takeaways

  • Execution is isolated - Each execution runs in its own sandbox, completely isolated from others

  • Parameters come from AI assistants - The params object contains data provided by the AI

  • Secrets come from workspace config - The config object contains your workspace secrets

  • Return standardized format - Always return { success, data } or { success, error }

  • Errors are caught automatically - But it's better to handle them in your code

  • Everything is logged - You can review execution logs to debug issues

  • Timeouts are enforced - Keep execution times under 30 seconds

Understanding the execution flow helps you write better tools, debug issues more effectively, and understand what's happening when your tools run.

Last updated