Skip to content

Basic Code Execution

Learn how to execute Node.js code using Actify's MCP tools.

Simple Execution

The most basic use case is executing JavaScript code and getting results:

typescript
// Ask your AI agent:
"Execute this code: console.log('Hello, World!')"

The agent uses the code_execute tool:

json
{
  "code": "console.log('Hello, World!');",
  "runtime": "node18"
}

Response:

json
{
  "executionId": "exec_abc123",
  "status": "completed",
  "logs": "Hello, World!\n",
  "credits": {
    "used": 10,
    "remaining": 990
  }
}

Returning Values

To get structured data back from your code:

javascript
const data = {
  message: 'Success',
  timestamp: Date.now(),
  environment: process.env.NODE_ENV
};

return data;

The returned value is available to the AI agent for further processing.

Using NPM Packages

Actify automatically installs NPM packages when you require them:

javascript
// The agent will auto-install axios
const axios = require('axios');

const response = await axios.get('https://api.github.com/repos/NatiSayada/actify');

return {
  name: response.data.name,
  stars: response.data.stargazers_count,
  language: response.data.language
};

Multiple Packages

javascript
const axios = require('axios');
const lodash = require('lodash');
const dayjs = require('dayjs');

const response = await axios.get('https://api.example.com/data');
const grouped = lodash.groupBy(response.data, 'category');
const formatted = dayjs().format('YYYY-MM-DD HH:mm:ss');

return { grouped, timestamp: formatted };

Working with Files

Create and read files in the execution environment:

javascript
const fs = require('fs').promises;

// Write JSON file
const data = { items: [1, 2, 3], total: 6 };
await fs.writeFile('/tmp/data.json', JSON.stringify(data, null, 2));

// Read it back
const content = await fs.readFile('/tmp/data.json', 'utf-8');
const parsed = JSON.parse(content);

return { success: true, data: parsed };

Text Processing

javascript
const fs = require('fs').promises;

// Create a text file
const text = `
Line 1: Hello
Line 2: World
Line 3: From Actify
`;

await fs.writeFile('/tmp/input.txt', text);

// Process it
const content = await fs.readFile('/tmp/input.txt', 'utf-8');
const lines = content.split('\n').filter(line => line.trim());
const processed = lines.map(line => line.toUpperCase());

return { original: lines, processed };

Error Handling

Always handle errors in your code:

javascript
try {
  const axios = require('axios');
  const response = await axios.get('https://api.example.com/data');

  return {
    success: true,
    data: response.data
  };
} catch (error) {
  return {
    success: false,
    error: error.message,
    stack: error.stack
  };
}

Async/Await Patterns

You can use async/await naturally:

javascript
const axios = require('axios');

async function fetchUserData(username) {
  const response = await axios.get(`https://api.github.com/users/${username}`);
  return response.data;
}

async function fetchRepos(username) {
  const response = await axios.get(`https://api.github.com/users/${username}/repos`);
  return response.data;
}

// Execute in parallel
const [user, repos] = await Promise.all([
  fetchUserData('octocat'),
  fetchRepos('octocat')
]);

return {
  user: { name: user.name, bio: user.bio },
  repoCount: repos.length,
  topRepos: repos.slice(0, 3).map(r => r.name)
};

Data Transformation

Common data processing patterns:

javascript
const data = [
  { id: 1, name: 'Alice', score: 85 },
  { id: 2, name: 'Bob', score: 92 },
  { id: 3, name: 'Charlie', score: 78 }
];

// Filter
const passing = data.filter(student => student.score >= 80);

// Map
const names = data.map(student => student.name);

// Reduce
const avgScore = data.reduce((sum, s) => sum + s.score, 0) / data.length;

return { passing, names, avgScore };

Working with APIs

GET Request

javascript
const axios = require('axios');

const response = await axios.get('https://api.github.com/repos/nodejs/node', {
  headers: {
    'Accept': 'application/vnd.github.v3+json'
  }
});

return {
  name: response.data.name,
  description: response.data.description,
  stars: response.data.stargazers_count
};

POST Request

javascript
const axios = require('axios');

const response = await axios.post('https://api.example.com/webhook', {
  event: 'test',
  timestamp: Date.now(),
  data: { key: 'value' }
}, {
  headers: {
    'Content-Type': 'application/json'
  }
});

return response.data;

Resource Limits

Control execution resources:

json
{
  "code": "/* your code */",
  "runtime": "node18",
  "params": {
    "cpu": "500m",
    "memory": "512Mi",
    "timeoutSeconds": 30
  }
}

When to Adjust Resources

  • CPU: Increase for computation-heavy tasks
  • Memory: Increase for large data processing
  • Timeout: Increase for slow API calls or large datasets
javascript
// CPU-intensive task
const result = [];
for (let i = 0; i < 1000000; i++) {
  result.push(Math.sqrt(i) * Math.PI);
}

return { computed: result.length };

Recommended params:

json
{
  "params": {
    "cpu": "1",
    "memory": "1Gi",
    "timeoutSeconds": 60
  }
}

Best Practices

  1. Always use try-catch for external calls
  2. Return structured data for better AI processing
  3. Log important steps with console.log
  4. Clean up temp files when done
  5. Set appropriate timeouts for your use case

Next Steps