Skip to content

Your First Tool

Tools let PIE take actions during conversations. They're JavaScript functions that run in a secure sandbox.

What Tools Do

  • Call external APIs
  • Process and transform data
  • Perform calculations
  • Interact with services

Create a Tool

Let's build a weather tool that fetches current weather data.

Step 1: Get an API Key

  1. Sign up at WeatherAPI.com
  2. Copy your API key

Step 2: Create the Agent

  1. Go to Agents in PIE
  2. Click Create Agent
  3. Select Tool tier

Step 3: Write the Code

js
/**
 * Weather Tool - Get current weather for any city
 */
async function handler(input, context) {
  const { city } = input;
  
  if (!city) {
    return { error: true, message: 'City is required' };
  }
  
  // Get API key from secrets
  const apiKey = context.secrets.WEATHER_API_KEY;
  
  if (!apiKey) {
    return { error: true, message: 'Weather API key not configured' };
  }
  
  // Make the API request using context.fetch()
  const response = await context.fetch(
    `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${encodeURIComponent(city)}`
  );
  
  if (!response.ok) {
    return { 
      error: true, 
      message: `Failed to fetch weather: ${response.status}` 
    };
  }
  
  // Parse the response
  const data = JSON.parse(response.body);
  
  // Return structured data for the AI
  return {
    city: data.location.name,
    country: data.location.country,
    temperature_c: data.current.temp_c,
    temperature_f: data.current.temp_f,
    condition: data.current.condition.text,
    humidity: data.current.humidity,
    wind_kph: data.current.wind_kph,
    feels_like_c: data.current.feelslike_c,
  };
}

module.exports = { handler };

Step 4: Define the Manifest

json
{
  "trigger": "auto",
  "developerSecrets": {
    "WEATHER_API_KEY": {
      "description": "API key from weatherapi.com",
      "required": true
    }
  },
  "tool": {
    "name": "get_weather",
    "description": "Get current weather conditions for a city. Use when users ask about weather.",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "City name (e.g., 'London', 'New York', 'Tokyo')"
        }
      },
      "required": ["city"]
    }
  }
}

Step 5: Add Your API Key

  1. After creating the agent, go to agent settings
  2. Add your WEATHER_API_KEY

Expose Heartbeat Events When It Makes Sense

Not every tool needs event triggers. Read-only tools like this weather example usually do not need heartbeatEvents.

If your tool performs meaningful mutations, publishes content, sends messages, or creates records, add a curated event catalog to the manifest so users can build Heartbeats from those actions:

json
{
  "heartbeatEvents": {
    "events": [
      {
        "id": "report_created",
        "displayName": "Report created",
        "description": "Fires when the tool creates a new report.",
        "enabled": true,
        "matchers": [
          { "source": "tool", "action": "create_report" }
        ]
      }
    ]
  }
}

PIE can suggest these events automatically when you save the plugin, but you should review the suggestions and keep only the user-facing outcomes you want to expose.

How Tools Work

  1. User asks: "What's the weather in Tokyo?"
  2. AI sees the get_weather tool description
  3. AI decides to call the tool with { city: "Tokyo" }
  4. PIE runs your handler in a sandbox
  5. Your code calls the weather API
  6. Results return to the AI
  7. AI formats a response for the user

Understanding the Handler

js
async function handler(input, context) {
  // input = parameters from the AI (e.g., { city: "Tokyo" })
  // context = PIE's API
  //   - context.fetch(url, options) - make HTTP requests
  //   - context.secrets - your API keys
  //   - context.user - user information
  
  return { /* data for the AI */ };
}

module.exports = { handler };

The Context Object

PropertyTypeDescription
context.fetch(url, options)FunctionMake HTTP requests
context.secretsObjectDeveloper secrets (API keys)
context.user.idStringCurrent user's ID
context.user.displayNameStringUser's display name
context.userConfigObjectUser-defined configuration values for this agent
context.userConfigObjectUser-configurable settings (from userFields in manifest)
context.oauth.*ObjectOAuth operations: isConnected(), fetch(), getConnectionInfo()
context.files.*ObjectFile storage: upload(), list(), get(), delete()
context.db.query()FunctionRun read-only SQL queries against external Postgres databases
context.tasks.*ObjectTask scheduling: create(), list(), update(), delete()

See the full Context API reference for details on all available properties and methods.

Security Scanning

When you create or update a tool, PIE automatically runs a security scan on your code. The scan checks for common security issues like data exfiltration, credential harvesting, and code injection. Your tool must pass all 10 security criteria to receive a "Verified" badge.

You can view scan results and manually trigger re-scans from the Security tab in the Developer Portal.

See the full Security Scanning guide for details.

Tips for Good Tools

  1. Clear descriptions - Help the AI know when to use your tool
  2. Validate input - Check for required parameters
  3. Handle errors - Return helpful error messages
  4. Return structured data - Let the AI format the response

Next Steps

Need a shareable frontend or public route for your tool? Read the Public Apps and Routes guide.

Ready for the advanced stuff? Let's build an OAuth connector.

Built with VitePress