Developing Scripts
This guide provides comprehensive documentation for creating and managing scripts in Mirra. It covers script structure, runtime environments, configuration options, version control, resource access, and best practices for production deployments.
Script Structure
Scripts consist of a handler function that receives event data and returns a result. The handler signature is consistent across both supported runtimes.
Node.js Handler
Parameters:
eventInput data object containing the trigger data. For manual executions, contains the data passed to the execute endpoint. For event-driven executions, contains normalized event fields and the full event object.
contextExecution context object with metadata about the script execution, including
scriptId,apiKey, andexecutionId.
Return Value:
The handler returns any JSON-serializable object. By convention, responses include a success boolean and a data object, but this structure is not enforced.
Python Handler
The Python handler follows the same parameter and return value conventions as Node.js.
Event Data Structure
Event-driven scripts receive normalized event data that works consistently across all trigger types. This enables scripts to handle multiple event sources without modification.
Normalized Fields
All events provide these standard fields:
Full Event Access
Power users can access the complete original event object:
Defensive Coding Pattern
Scripts can use defensive patterns to handle any trigger type:
This approach enables zero-configuration scripts that work with any trigger without setup, making them naturally reusable and LLM-friendly.
Runtime Environments
Mirra supports two runtime environments with different capabilities and package ecosystems.
Node.js 18
The Node.js runtime provides modern JavaScript and TypeScript support with access to popular NPM packages.
Features:
- TypeScript support with type checking
- ES modules and CommonJS
- Async/await and Promises
- NPM package ecosystem
- 30-second default timeout
Available Packages:
Standard Node.js built-ins and popular packages including:
lodash- Utility functionsaxios- HTTP clientdate-fns- Date manipulationuuid- UUID generationcrypto- Cryptographic functions
Example with External Package:
Python 3.11
The Python runtime provides modern Python syntax with async/await support and access to popular pip packages.
Features:
- Modern Python 3.11 syntax
- Type hints and annotations
- Async/await support
- Pip package ecosystem
- 30-second default timeout
Available Packages:
Standard Python library and popular packages including:
requests- HTTP clientpandas- Data analysisnumpy- Numerical computingdatetime- Date and time utilitiesjson- JSON encoding/decoding
Example with External Package:
Configuration
Scripts accept configuration parameters that control execution behavior, resource access, and cost limits.
Configuration Object
Configuration Parameters
runtimeExecution environment. Must be
"nodejs18"or"python3.11". Default:"nodejs18".Choose based on your preferred language and required packages. Both runtimes provide equivalent functionality through the Mirra SDK.
timeoutMaximum execution time in seconds. Range: 1-300. Default: 30.
Scripts exceeding this limit are terminated with a timeout error. Increase for long-running operations like large data processing or external API calls with slow response times.
memoryMemory allocation in MB. Range: 128-3008. Default: 128.
Higher memory allocation provides proportionally more CPU. Increase for memory-intensive operations like large dataset processing or complex computations.
maxCostPerExecutionMaximum cost per execution in USD. Default: 1.0.
Executions exceeding this limit fail with a cost limit error. This prevents runaway costs from expensive resource calls or long execution times.
maxExecutionsPerDayMaximum executions per 24-hour period. Default: 100.
Scripts stop executing when this limit is reached until the next day. This prevents excessive costs from high-frequency event triggers.
allowedResourcesArray of resource IDs the script can access. Empty array (default) denies all resource access.
Scripts can only call resources explicitly whitelisted in this array. See Resources for details on creating and using resources.
Updating Configuration
Update script configuration using the PATCH endpoint:
Configuration changes take effect immediately for new executions. In-progress executions use the configuration active at execution start.
Version Control
Scripts support version control for safe deployments and rollbacks. Each version is immutable once created.
Creating Versions
Create a new version with updated code:
Response:
Listing Versions
Retrieve all versions for a script:
Deploying Specific Versions
Deploy a specific version by including the version number:
Omitting the version number deploys the latest version.
Accessing Resources
Scripts access external APIs through Resources. Resources encapsulate API credentials and provide a secure interface for making external calls.
Granting Resource Access
Add resource IDs to the script's allowedResources configuration:
Calling Resources
Use the Mirra SDK to call resources from within scripts:
Scripts can only access resources explicitly listed in allowedResources. Attempts to call non-whitelisted resources fail with a permission error.
Using the Mirra SDK
Scripts have access to the mirra global object, which provides methods for interacting with Mirra services.
Memory Operations
Store and retrieve data in Mirra memory:
Telegram Operations
Send messages and interact with Telegram:
Calendar Operations
Create and manage calendar events:
Gmail Operations
Send emails and manage Gmail:
Best Practices
Error Handling
Always wrap script logic in try-catch blocks to handle errors gracefully:
This pattern ensures scripts always return a response, even when errors occur, making debugging easier.
Logging
Use console methods for debugging and monitoring:
All console output is captured in execution logs and available through the SDK API.
Performance Optimization
Initialize expensive resources outside the handler function to reuse them across invocations:
The Mirra platform reuses execution containers across invocations, so global variables persist between executions.
Timeout Management
For long-running operations, implement timeout handling to prevent execution termination:
Memory Management
Process large datasets in batches to avoid memory limits:
Script Lifecycle
Scripts progress through several states during their lifecycle:
Draft
Initial state after creation. Scripts in draft state:
- Have not been deployed
- Cannot be executed
- Can have code modified freely
- Do not consume resources
Deployed
Active state after deployment. Scripts in deployed state:
- Are deployed to the Mirra platform
- Can be executed manually via API
- Can subscribe to events
- Consume resources during execution
Published
Optional state for marketplace scripts. Published scripts:
- Appear in marketplace listings
- Can be installed by other users
- Support monetization (free, pay-per-execution, subscription)
- Cannot have code modified (create new versions instead)
Archived
Final state for retired scripts. Archived scripts:
- Cannot be executed
- Preserve execution history
- Can be restored to deployed state
- Do not consume resources
Updating Scripts
Update Metadata
Modify script name, description, or other metadata:
Update Code
Create a new version with updated code, then deploy:
Deleting Scripts
Delete a script and all associated data:
This operation:
- Deletes the script and all versions
- Deletes execution history
- Removes all event subscriptions
- Removes the deployed function from the platform
This action cannot be undone! Ensure you want to permanently delete the script and all associated data.
Advanced Patterns
Stateful Scripts
Use memory to maintain state across executions:
Conditional Execution
Implement business logic to control when scripts execute:
Chaining Scripts
Execute multiple scripts in sequence:
Monitoring and Debugging
View Metrics
Retrieve execution metrics for monitoring:
Response:
View Execution Details
Retrieve detailed information for a specific execution:
The response includes:
- Complete execution logs
- Error stack traces
- Resource call details
- Duration and cost breakdown
- Trigger information
Troubleshooting
Timeout Errors
Symptoms: Script fails with timeout error
Solutions:
- Increase timeout in configuration (up to 300 seconds)
- Optimize slow operations (database queries, API calls)
- Use async operations properly to avoid blocking
- Cache expensive computations outside the handler
Example Fix:
Memory Errors
Symptoms: Out of memory errors during execution
Solutions:
- Increase memory allocation in configuration
- Process data in smaller batches
- Avoid loading large files entirely into memory
- Use streaming for large datasets
Example Fix:
Deployment Failures
Symptoms: Deploy endpoint returns an error
Solutions:
- Verify code syntax is valid
- Ensure all dependencies are available in the runtime
- Check that runtime matches code language
- Review deployment error messages for specific issues
Event-Driven Scripts Not Executing
Symptoms: Events occur but script doesn't run
Solutions:
- Verify script is deployed (check deployment status)
- Confirm subscription is enabled
- Check event type matches subscription
- Verify conditions match event data
- Ensure daily execution limit hasn't been reached
Security
API Key Management
Each script has a unique API key for execution. The key is available in the execution context:
Note: The script API key is different from your user API key. Script keys are scoped to individual scripts and cannot access other user resources.
Resource Access Control
Scripts can only access resources explicitly whitelisted in the allowedResources configuration. This prevents unauthorized access to sensitive APIs and credentials.
Attempts to call non-whitelisted resources fail with a permission error.
User Isolation
Scripts execute only for their owner's events:
- ✅ Your script receives your Telegram messages
- ❌ Your script cannot receive other users' messages
- ✅ Your script accesses your calendar events
- ❌ Your script cannot access other users' calendars
Cost Management
Understanding Costs
Script execution costs include:
- Compute time - Based on memory allocation and execution duration
- Resource calls - API calls made through resources
- Storage - Logs and execution history
Typical costs:
- Simple script (128MB, <1s): ~$0.0001 per execution
- Complex script (512MB, 10s): ~$0.001 per execution
- Resource-heavy script: $0.01+ per execution
Setting Budgets
Control costs with execution and cost limits:
Scripts stop executing when either limit is reached.
Monitoring Costs
Track spending through metrics:
Review totalCost and avgDuration to identify expensive scripts.
Publishing to Marketplace
Make Script Public
Publish a script to the marketplace:
Pricing Models
Free:
Pay-Per-Execution:
Subscription:
Private Scripts
Keep scripts private (not listed in marketplace):
See Also
- Scripts Overview - High-level overview of scripts capabilities
- Quickstart Guide - Create your first script in 5 minutes
- Event-Driven Scripts - Complete event subscription documentation
- Resources - Access external APIs from scripts
- Templates - Bundle scripts with resources for distribution
- SDK API Reference - Complete API documentation