> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Importly with Mastra

> Give your Mastra agent tools that transcribe, download and describe any video or audio link: three createTool() definitions over the REST API and an agent that uses them.

If your app runs a [Mastra](https://mastra.ai) agent and users send it video or podcast links, the agent needs a way to read them. Fetching the media yourself tends to break once the app is deployed: sites block the datacenter IPs your server runs on, and many videos have no captions. Give the agent Importly tools instead. They call the REST API from your server and return the transcript, a download link for the file, or the video's details.

This page uses plain `createTool()` definitions, so the only packages you need are `@mastra/core` and `zod`.

## 1. Store your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once) and add it to your server environment, next to your model provider's key:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
```

The tools run where your Mastra server runs, so the key never reaches the browser.

## 2. Define the tools

Each tool starts an Importly job and polls its status until it finishes. A transcript of a video with captions usually comes back within the first request, because `wait` holds it open for up to 30 seconds.

```ts src/mastra/tools/importly.ts theme={null}
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

const API = 'https://api.importly.io'

type Job = { jobId: string, status: string, result?: Record<string, unknown> }

const call = async (method: 'GET' | 'POST', path: string, body?: object): Promise<Job> => {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body ? JSON.stringify(body) : undefined,
  })
  const json = await res.json()
  if (!json.success) throw new Error(`${json.code}: ${json.error}`)
  return json.data
}

// Start a job, then poll until it finishes (or return the jobId after about 2 minutes)
const runJob = async (path: string, body: object): Promise<Job> => {
  let job = await call('POST', path, body)
  for (let i = 0; i < 40 && job.status !== 'completed' && job.status !== 'failed'; i++) {
    await new Promise((resolve) => setTimeout(resolve, 3000))
    job = await call('GET', `${path}/status?id=${job.jobId}`)
  }
  return job
}

export const transcribeMedia = createTool({
  id: 'transcribe-media',
  description:
    'Transcribe a video or audio link (YouTube, TikTok, X, Instagram, podcasts and 1,000+ other sites). ' +
    'Returns the text and timestamped segments.',
  inputSchema: z.object({
    url: z.string().describe('Public page URL of the video or audio'),
    language: z.string().optional().describe('Language hint, e.g. "en"'),
  }),
  execute: async ({ url, language }) =>
    runJob('/transcribe', { url, language, mode: 'auto', wait: 30, maxCostDollars: 0.5 }),
})

export const importMedia = createTool({
  id: 'import-media',
  description: 'Download the video or audio behind a link and return a download URL for the file, with its title.',
  inputSchema: z.object({
    url: z.string().describe('Public page URL of the video or audio'),
    audioOnly: z.boolean().optional().describe('Download only the audio'),
  }),
  execute: async ({ url, audioOnly }) =>
    runJob('/import', { url, includeVideo: !audioOnly, videoQuality: '720p', maxCostDollars: 1 }),
})

export const getMediaDetails = createTool({
  id: 'get-media-details',
  description: 'Get the title, duration and thumbnail of a video or audio link.',
  inputSchema: z.object({
    url: z.string().describe('Public page URL of the video or audio'),
  }),
  execute: async ({ url }) => runJob('/metadata/basic', { url }),
})
```

`maxCostDollars` caps what one call can spend. If a job would cost more, it fails with [`MAX_COST_EXCEEDED`](/docs/errors/max-cost-exceeded) and the price instead of running. Raise the caps to suit your app. `mode: 'auto'` uses the video's captions when it has them and speech-to-text when it doesn't.

## 3. Give the tools to an agent

```ts src/mastra/agents/media-agent.ts theme={null}
import { Agent } from '@mastra/core/agent'
import { transcribeMedia, importMedia, getMediaDetails } from '../tools/importly'

export const mediaAgent = new Agent({
  id: 'media-agent',
  name: 'Media agent',
  instructions:
    'When the user sends a video or audio link, use transcribe-media to read it. ' +
    'Use import-media only when they ask for the file, and get-media-details for title or length questions.',
  model: 'openai/gpt-5-mini',
  tools: { transcribeMedia, importMedia, getMediaDetails },
})
```

Register it on your Mastra instance:

```ts src/mastra/index.ts theme={null}
import { Mastra } from '@mastra/core'
import { mediaAgent } from './agents/media-agent'

export const mastra = new Mastra({
  agents: { mediaAgent },
})
```

Then call it from your app's backend, for example to summarize the video behind a link:

```ts src/summarize.ts theme={null}
import { mastra } from './mastra'

export const summarize = async (url: string) => {
  const agent = mastra.getAgent('mediaAgent')
  const result = await agent.generate(`Transcribe ${url} and summarize it in five bullet points.`, {
    maxSteps: 3,
  })
  return result.text
}
```

The agent calls `transcribe-media`, reads `result.text`, and answers in the next step. `maxSteps` lets it take more than one step, which it needs to use a tool result. Swap in any model your Mastra setup supports. The same agent works with `agent.stream()` for a chat UI, and in Mastra Studio while you develop. These examples typecheck against `@mastra/core` 1.85.

## What each tool returns

The tools hand the job object back to the agent:

| Tool | Endpoint | `result` when `status` is `completed` |
| - | - | - |
| `transcribe-media` | [`POST /transcribe`](/docs/endpoints/transcribe) | `text`, `language`, `source` (captions or speech-to-text) and `data.segments` with start and end times |
| `import-media` | [`POST /import`](/docs/endpoints/import) | `mediaUrl` (a download link for the file) and `title` |
| `get-media-details` | [`POST /metadata/basic`](/docs/endpoints/basic-metadata) | `title`, `duration`, `thumbnail` |

A job that can't finish, for example because the video is private, comes back with `status: 'failed'` and a `code` the agent can explain to the user ([error codes](/docs/error-handling.md)). A long download may still be `running` when the tool stops polling. For files, a [webhook](/docs/webhooks.md) is the better fit in production: start the import from your backend, store the `jobId`, and save `mediaUrl` when the webhook arrives. The [Next.js guide](/docs/integrations/nextjs.md) shows that flow.

## Costs

Each tool call is billed like the same API request: a caption transcript is $0.003, speech-to-text $0.01 a minute, and downloads are priced by size. See [Billing](/docs/billing.md). Importly is free to try, no card required.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.