Creating Scripts (Portal)
A script is executable code that runs in a sandboxed environment on Mirra's infrastructure. This guide covers everything you need to create, test, and publish scripts on the Mirra Store.
By the end of this guide, you will understand how to write scripts in Node.js or Python, configure execution limits, test your code, implement error handling, and publish your script to the marketplace.
What is a script?
A script is custom code that runs on the Mirra platform to automate tasks, process data, and integrate services. Scripts execute in a secure, isolated environment with configurable resource limits.
How scripts work
When you create a script, you define:
- Execute function - The main function that processes input parameters
- Runtime - Node.js 18 (JavaScript/TypeScript) or Python 3.11
- Execution limits - Timeout, memory, and cost constraints
- Input parameters - The data your script accepts
- Return value - The results your script produces
Users execute your script through their agents by providing parameters. The platform runs your code, captures the output, and returns the results.
What scripts can do
Scripts are ideal for:
- Data processing - Transform, analyze, or enrich data between formats
- Task automation - Schedule and execute workflows automatically
- Service integration - Connect multiple APIs into a single operation
- Custom logic - Implement business-specific functionality not available in existing services
Prerequisites
Before creating a script, ensure you have:
- Code to automate - A clear understanding of what your script should do
- Runtime knowledge - Familiarity with JavaScript/TypeScript (Node.js) or Python
- Test data - Sample inputs for testing your script
- Error handling plan - How your script should handle invalid inputs or failures
Scripts run in a sandboxed environment with limited access to external resources. You cannot access the file system, make arbitrary network requests, or use certain system calls.
Supported runtimes
The developer portal supports two runtime environments for scripts.
Node.js 18 (JavaScript/TypeScript)
Node.js 18 provides a modern JavaScript runtime with full ES2022 support.
Features:
- Modern JavaScript features (async/await, destructuring, optional chaining)
- TypeScript support with automatic transpilation
- NPM packages available (limited to approved packages)
- Fast execution with V8 engine
- JSON processing and manipulation
Best for:
- Web API integration and data transformation
- JSON processing and manipulation
- Modern workflows with async operations
- Developers familiar with JavaScript/TypeScript
Available packages: lodash, axios, date-fns, uuid, crypto-js
Contact support to request additional packages for your scripts.
Creating a script
Follow these steps to create and publish a script on the Mirra Store.
Navigate to scripts
- Open the Developer Dashboard
- Click "Scripts" in the sidebar navigation
- Click the "Create Script" button
- Alternatively, use the keyboard shortcut
Ctrl+Shift+N
The script editor opens with the Monaco code editor and configuration fields.
Fill in basic information
Provide essential metadata about your script:
Field requirements:
- Name - Unique, descriptive name (3-50 characters)
- Description - Clear explanation of what your script does (10-500 characters)
- Runtime - Choose
nodejs18(JavaScript/TypeScript) orpython3.11(Python)
Choose a runtime based on your familiarity and the task requirements. Node.js is better for JSON processing and web APIs, while Python excels at data processing and scientific computing.
Write your code
Use the Monaco code editor with full IDE features including syntax highlighting, autocomplete, error detection, and inline documentation.
Node.js example
Python example
Function requirements:
- Function name - Must be named
execute(required) - Parameters - Accepts a single
paramsobject with user-provided data - Return value - Must return a JSON-serializable object (dict, list, string, number, boolean, or null)
- Error handling - Throw exceptions for invalid inputs or execution failures
The platform calls your execute function with user parameters and returns the result to the agent.
Configure execution limits
Set resource limits to control costs and prevent abuse:
Configuration options:
- Timeout - Maximum execution time in seconds (range: 1-300, default: 30)
- Memory - RAM limit in megabytes (range: 128-2048, default: 256)
- Max cost per execution - Maximum cost per single execution (default: $0.10)
- Max executions per day - Daily execution limit to prevent abuse (default: 1000)
- Allowed resources - List of resource IDs this script can access (optional)
These limits protect both you and your users from unexpected costs and resource usage. Set conservative limits initially and increase them based on actual usage patterns.
Configure trigger and setup
Define how your script can be triggered and what inputs users need to configure when creating automations.
Trigger Configuration
Specify which trigger types your script supports:
Trigger types:
event- Triggered by system events (messages, emails, calendar events)schedule- Triggered on a schedule (cron expression)manual- Triggered by user button press or actionapi- Triggered by API calls
For event-triggered scripts:
eventTypes- Array of event types this script handles (see Event Catalog)sources- Array of event sources (e.g.,telegram,google-gmail,google-calendar)
Available Event Types:
telegram.message,telegram.commandgmail.email_receivedcalendar.event_created,calendar.event_updated,calendar.event_deletedcall.started,call.ended,transcript.chunk
For schedule-triggered scripts:
defaultSchedule- Default cron expression (e.g.,"0 9 * * *"for 9 AM daily)
Script Variables
Define variables that users configure when setting up automations. These variables are passed to your script at runtime via the event parameter.
How it works:
- You define variables (name, type, description)
- Users configure values when creating automations
- Your script accesses values via
event.variableName
Example variable definition:
Accessing in your script:
Variable types:
text- Text input fieldnumber- Numeric inputboolean- Checkbox/toggleselect- Dropdown with predefined optionsresource_selector- Dynamic dropdown that fetches resources (chats, channels, labels)
Resource types for resource_selector:
telegram_chat- Telegram chats/channelstelegram_user- Telegram usersgmail_label- Gmail labelsslack_channel- Slack channels
Variable fields:
name- Variable name accessible asevent.variableNamein your scriptdisplayName- Human-readable label shown to userstype- Variable type (see above)required- Whether this field must be filleddescription- Help text explaining what this variable doesplaceholder- Placeholder text for the inputhelpText- Additional context or tipsdefault- Default value if user doesn't provide one
UI Configuration
Configure how your script appears in different interfaces, especially the mobile app:
Configuration options:
quickSetupAvailable- Enable simplified mobile setup flow (auto-configures triggers)category- Script category:notification,data_sync,automation,utility,reportingicon- Emoji or icon identifier displayed in listsflowDescription- Short description of what the script doesexampleUseCase- Example use case to help users understand the value
Complete Example: Email to Telegram Script
Here's a complete script configuration for an email-to-Telegram notification script:
With this configuration:
- Users creating automations will only see scripts compatible with their selected trigger type
- The mobile app will automatically configure the email.received event trigger
- Users only need to select which Telegram chat to use
- The setup process is simplified from 6 steps to just 2-3 steps
Test your script
Use the built-in testing tools to verify your script works correctly:
- Click the "Test" button in the editor toolbar
- Provide test parameters in JSON format:
- Click "Run Test" to execute your script
- View the execution results:
- Check execution logs for console output and errors
- Verify execution time and memory usage
- Test with edge cases (empty input, very long input, special characters)
- Test error handling with invalid inputs
Test thoroughly before publishing. Verify your script handles all expected inputs, edge cases, and error conditions correctly.
Testing checklist:
- ✅ Valid inputs produce correct results
- ✅ Invalid inputs throw descriptive errors
- ✅ Edge cases are handled properly
- ✅ Execution completes within timeout limit
- ✅ Memory usage stays within limit
- ✅ Error messages are helpful and clear
Publish your script
When your script is ready, publish it to make it available to users:
- Review all configuration and code
- Ensure all tests pass successfully
- Verify execution limits are appropriate
- Click "Publish" to make your script live
- Your script appears in the marketplace immediately
Post-publishing checklist:
- ✅ Script appears in marketplace search
- ✅ Users can view documentation and examples
- ✅ Users can execute the script through their agents
- ✅ Executions are tracked and billed correctly
- ✅ Error handling works as expected
Your script is now live in the marketplace! Users can execute it through their agents.
Script structure
Understanding the required structure for scripts helps you write code that works correctly with the platform.
Required function signature
Every script must export an execute function with a specific signature:
Requirements:
- Function name must be
execute - Can be
asyncor synchronous - Accepts single
paramsparameter - Must be exported via
module.exports
Input parameters
The params object contains user-provided input data. Always validate parameters before processing to ensure your script handles invalid inputs gracefully.
Example input:
Validation pattern:
Return values
Return a JSON-serializable object containing your results. The platform converts your return value to JSON and sends it to the user's agent.
Valid return types:
- Objects (dictionaries)
- Arrays (lists)
- Strings
- Numbers
- Booleans
null
Example return value:
Invalid return types:
- Functions
- Undefined
- Circular references
- Binary data (use base64 encoding instead)
Error handling
Throw descriptive errors for invalid inputs or execution failures. The platform catches exceptions and returns error messages to users.
Best practices:
- Use descriptive error messages
- Include parameter names in validation errors
- Catch and re-throw with context
- Don't expose sensitive information in errors
Version control
The developer portal includes version control for scripts, allowing you to track changes and roll back if needed.
Creating a new version
Save a new version of your script when you make significant changes:
- Edit your script code in the editor
- Click "Save New Version" in the toolbar
- Enter a descriptive commit message:
- The new version is created and saved
Commit message best practices:
- Start with a prefix:
Fix:,Add:,Update:,Remove: - Be specific about what changed
- Keep messages under 72 characters
- Reference issue numbers if applicable
Viewing version history
View all versions of your script and their changes:
-
Click the "Versions" tab in the editor
-
View the version list with:
- Version number - Sequential version identifier (v1, v2, v3, etc.)
- Commit message - Description of changes
- Timestamp - When the version was created
- Author - Who created the version
-
Click on a version to view its code
Rolling back to a previous version
Restore a previous version if you need to undo changes:
- Select the previous version from the version list
- Click "Restore This Version"
- Confirm the action in the dialog
- The selected version becomes the current version
Published scripts always use the latest version. When you restore a previous version, it becomes the new latest version and users will execute that code.
Version control tips:
- Create versions before major changes
- Test thoroughly before creating a new version
- Use descriptive commit messages
- Keep a changelog of significant changes
Testing strategies
Comprehensive testing ensures your script works correctly for all inputs and edge cases.
Unit testing
Test individual functions and logic in isolation:
Unit testing best practices:
- Test each function independently
- Use descriptive test names
- Test both success and failure cases
- Verify edge cases and boundary conditions
Integration testing
Test with real data to verify end-to-end functionality:
Integration testing best practices:
- Use realistic test data
- Test the complete execute function
- Verify result structure and types
- Test with data from actual use cases
Edge case testing
Test boundary conditions and unusual inputs:
Edge case testing checklist:
- ✅ Empty strings and arrays
- ✅ Very long inputs (stress testing)
- ✅ Special characters and punctuation
- ✅ Unicode and emoji characters
- ✅ Missing required parameters
- ✅ Invalid parameter types
- ✅ Null and undefined values
- ✅ Extreme numbers (very large, very small, negative)
Publishing your script
Publishing makes your script available to all users in the marketplace.
Pre-publishing checklist
Before publishing, ensure your script meets these requirements:
- ✅ All tests pass successfully
- ✅ Error handling covers all edge cases
- ✅ Execution limits are appropriate
- ✅ Code is well-documented with comments
- ✅ Description clearly explains functionality
- ✅ Examples demonstrate common use cases
Publishing process
- Review all configuration and code one final time
- Test with multiple input scenarios
- Verify execution time and memory usage
- Click "Publish" in the editor toolbar
- Confirm publishing in the dialog
- Your script goes live immediately
After publishing
Once published, your script is immediately available to users:
- ✅ Script appears in marketplace search results
- ✅ Users can view documentation and examples
- ✅ Users can execute your script through their agents
- ✅ Execution tracking begins automatically
- ✅ Users can submit reviews and ratings
- ✅ Revenue tracking starts (for paid scripts)
Monitor your script's performance and user feedback to identify improvements.
Best practices
Follow these best practices to create high-quality, reliable scripts.
Code quality
Write clean, maintainable code that is easy to understand and modify:
- Use descriptive names - Choose clear variable and function names that explain their purpose
- Add comments - Explain complex logic and non-obvious decisions
- Follow conventions - Use language-specific style guides (ESLint for JavaScript, PEP 8 for Python)
- Keep functions focused - Each function should do one thing well
- Avoid duplication - Extract repeated code into reusable functions
Example:
Performance optimization
Optimize your code to reduce execution time and memory usage:
- Choose efficient algorithms - Use appropriate data structures and algorithms for your task
- Avoid unnecessary loops - Combine operations when possible
- Cache repeated calculations - Store results of expensive operations
- Process data in batches - Handle large datasets incrementally
- Monitor resource usage - Track execution time and memory consumption
Example:
Security considerations
Protect your script and users from security vulnerabilities:
- Validate all inputs - Check types, ranges, and formats before processing
- Sanitize user data - Remove or escape potentially dangerous content
- Avoid eval() or exec() - Never execute user-provided code
- Don't log sensitive data - Avoid logging passwords, API keys, or personal information
- Use approved packages - Only use packages approved by the platform
Example:
Error handling best practices
Implement robust error handling to improve user experience:
- Catch all exceptions - Handle both expected and unexpected errors
- Provide helpful messages - Explain what went wrong and how to fix it
- Log errors for debugging - Include context and stack traces in logs
- Don't expose internals - Avoid revealing implementation details in error messages
- Return consistent formats - Use a standard error response structure
Example:
Documentation practices
Document your script to help users understand how to use it:
- Document parameters - Explain what each parameter does and its expected format
- Explain return values - Describe the structure and meaning of return data
- Provide usage examples - Show common use cases with sample inputs and outputs
- List dependencies - Note any required resources or external services
- Include troubleshooting tips - Help users resolve common issues
Troubleshooting
Common issues when creating scripts and their solutions.
Timeout errors
Problem: Your script exceeds the execution time limit.
Solutions:
- Optimize your code - Reduce algorithmic complexity and eliminate unnecessary operations
- Process data incrementally - Handle large datasets in smaller chunks
- Cache expensive operations - Store and reuse results of repeated calculations
- Request higher limits - Contact support to increase timeout limits for your account
- Split into smaller scripts - Break complex operations into multiple scripts
Example optimization:
Memory errors
Problem: Your script runs out of memory.
Solutions:
- Process data in chunks - Handle large datasets incrementally instead of loading everything at once
- Release unused variables - Set large variables to
nullwhen no longer needed - Use efficient data structures - Choose appropriate data structures for your use case
- Stream data - Process data as it arrives instead of buffering everything
- Request more memory - Contact support to increase memory limits
Example:
Import errors
Problem: Cannot import required packages.
Solutions:
- Use approved packages only - Check the list of available packages for your runtime
- Verify package names - Ensure you're using the correct package name and import syntax
- Contact support - Request new packages to be added to the approved list
- Use built-in modules - Prefer standard library modules when possible
Available packages:
- Node.js:
lodash,axios,date-fns,uuid,crypto-js - Python:
requests,pandas,numpy,dateutil,pydantic
Execution errors
Problem: Script fails during execution with unexpected errors.
Solutions:
- Add comprehensive error handling - Catch and handle all possible exceptions
- Validate inputs thoroughly - Check all parameters before processing
- Test with edge cases - Verify your script handles unusual inputs correctly
- Check execution logs - Review logs for detailed error messages and stack traces
- Add defensive programming - Check for null/undefined values before accessing properties
Next steps
Now that you understand how to create scripts, explore these related topics:
- Managing Your Profile - Optimize your developer profile
- Handling Reviews - Engage with users and respond to feedback
- Best Practices - Tips for building successful integrations
- Creating Resources - Build API integrations that your scripts can use
See also
- Core Concepts: Scripts - Understanding scripts in depth
- Examples: Scripts - Working script examples with complete code
- Core Concepts: Script Events - Using event-driven scripts
- Getting Started Guide - Complete developer portal walkthrough
- Developer Portal Introduction - Overview of the developer portal