# Pull analytics across all accounts with Vercel AI SDK

Source: https://developers.tokportal.com/agents/vercel-ai-sdk/analytics-multi-account/
Markdown: https://developers.tokportal.com/agents/vercel-ai-sdk/analytics-multi-account.md

From Vercel AI SDK, one call summarizes every managed account: `get_analytics_dashboard` (filters `platform`, `country`, `account`, `from`/`to`), `get_analytics_series` for daily or weekly curves of views/likes/comments/shares/followers, `list_account_video_analytics` per account, `get_comment_pulse` for what people say, and `export_analytics_videos` / `create_analytics_report` for the CSV or branded report. TokPortal collects the numbers because it operates the accounts — no per-account OAuth, no Business-account requirement, no scraping on your side.

## Connect TokPortal to Vercel AI SDK

Vercel AI SDK is an agent framework (code): TypeScript toolkit for AI apps; the MCP client (`@ai-sdk/mcp`, formerly `experimental_createMCPClient` in `ai`) turns TokPortal tools into `generateText`/`streamText` tools.

```bash
npm i ai @ai-sdk/mcp @modelcontextprotocol/sdk @ai-sdk/anthropic
```

```ts
import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { createMCPClient } from '@ai-sdk/mcp';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

const mcpClient = await createMCPClient({
  transport: new StreamableHTTPClientTransport(
    new URL('https://app.tokportal.com/api/ext/mcp'),
    { requestInit: { headers: { 'X-API-Key': process.env.TOKPORTAL_API_KEY! } } },
  ),
});

try {
  const tools = await mcpClient.tools();
  const { text } = await generateText({
    model: anthropic('claude-sonnet-4-5'),
    tools,
    prompt: 'List my published TokPortal bundles and their video counts.',
  });
  console.log(text);
} finally {
  await mcpClient.close();
}
```

On AI SDK 5 the import is `import { experimental_createMCPClient as createMCPClient } from 'ai'`; the rest is identical.

Snippet status: **verified** against Vercel AI SDK's documentation ([source](https://ai-sdk.dev/docs/ai-sdk-core/mcp-tools)).

Once connected, sanity-check the setup with a read-only call: "What is my TokPortal credit balance?" should trigger `tokportal_get_credit_balance`. GET requests and dry-run writes do not spend credits.

## Try the workflow without spending

For this trial, use the remote MCP endpoint `https://app.tokportal.com/api/ext/mcp`, local `tokportal-mcp` **1.15.1 or later**, or the REST API. Upgrade and restart an older local server first. Version 1.15.0 does not forward the dry-run header; do not use its write tools for a simulation. If you cannot verify the installed local version, use the remote endpoint or REST.

Use the [sandbox](https://developers.tokportal.com/sandbox) for the first attempt. MCP write tools accept `dry_run: true` as a top-level argument, beside `body`; REST writes accept the `X-TokPortal-Dry-Run: true` header. Keep your usual authentication and scopes. Each simulated write validates the request and returns `credits_would_charge` with `credits_charged: 0`. Nothing is created or published.

Simulated IDs start with `00000000-0000-4000-8000-`. Use them only in later dry-run writes. GET requests read real data, so skip publish-readiness checks and polling for synthetic IDs. Simulations have no cross-call memory and upload URLs are placeholders: do not upload files to them.

To run for real, review the returned price and confirm **before the first live write**. Bundle creation charges credits immediately; publishing hands the order to a manager. Repeat creation without dry-run mode and use the new real IDs for configuration and publishing. A synthetic ID cannot be reused in a live request.

## How it works

Analytics in TokPortal are workspace-wide and account-scoped at once. Start with `get_analytics_contract` once — it tells the agent which metrics, granularities and freshness guarantees apply to your workspace — then `get_analytics_dashboard` for the headline numbers over `from`/`to`, filtered by repeatable `platform`, `country` and `account` params. `get_analytics_series` returns time series with `metric` (`views`, `likes`, `comments`, `shares`, `followers`), `granularity` (`day`, `week`) and `mode` (`cumulative`, `gained`, `snapshot`) — `gained` per day is what most dashboards want.

Per account, `get_analytics_account` (or `get_account_analytics`) gives the profile-level snapshot and `list_account_video_analytics` the per-video table (paginated, `sort_by`/`sort_order`), which the agent can rank to find winning hooks. Comments: `get_comment_pulse` for the aggregate mood and `list_analytics_account_comments` for the text. If a number looks stale, `can_refresh_account_analytics` says whether a refresh is allowed and `refresh_account_analytics` triggers it — refreshes are rate-limited by design.

For deliverables, `export_analytics_videos` returns a CSV filtered by `account`, `platform`, `country`, `q`, `from`, `to`; `create_analytics_report` returns a structured report and `export_analytics_report_html` a branded HTML page. From Vercel AI SDK the useful pattern is a scheduled digest: every morning, dashboard for yesterday, top 5 videos, accounts with zero posts in 7 days (join with `list_accounts`), any new entries in `list_account_bans` — posted to Slack or written to a sheet.

## Run it from Vercel AI SDK

With Vercel AI SDK the sequence is driven by your code: give the agent the tools from the TokPortal MCP server and the prompt below as the user message (or split it into tasks). Log every `tokportal_*` call and its arguments in development — the tool list is large (91 tools), so consider filtering to the ones this job needs.

**Tool sequence**

1. `tokportal_get_analytics_contract` — Metrics, granularities and freshness rules for your workspace.
2. `tokportal_get_analytics_dashboard` — Totals over `from`/`to` with `platform`/`country`/`account` filters.
3. `tokportal_get_analytics_series` — `metric`, `granularity`, `mode`, optional `account`.
4. `tokportal_list_accounts` — Enumerate accounts (`platform`, `country`, `banned=false`) to iterate.
5. `tokportal_list_account_video_analytics` — Per-video table per account, sortable.
6. `tokportal_get_comment_pulse` — Aggregate comment signal across accounts.
7. `tokportal_refresh_account_analytics` — Force a refresh when `can_refresh_account_analytics` allows.
8. `tokportal_export_analytics_videos` — CSV for spreadsheets.
9. `tokportal_create_analytics_report` — Structured report (or `export_analytics_report_html`).

**Prompt to paste**

```text
Evaluate this workflow in the TokPortal sandbox only.
Use the remote MCP endpoint https://app.tokportal.com/api/ext/mcp or local tokportal-mcp 1.15.1 or later for write tools.
Verify the installed local version before using its write tools. Version 1.15.0 is unsafe for simulations.
If the local version is older or unknown, use the remote endpoint or authenticated REST
requests with X-TokPortal-Dry-Run: true instead.
For every non-GET MCP tool call, set dry_run: true as a top-level boolean beside body.
For every REST write in a workflow, send the X-TokPortal-Dry-Run: true header.
Use normal read tools for existing real objects. Do not GET or poll synthetic IDs,
and do not upload files to simulated upload URLs. Simulated objects have no cross-call memory.
Show credits_would_charge and verify credits_charged is 0 for each simulated write.
Do not execute any live write. Ask for my explicit GO before the first real write,
including bundle creation, which charges immediately. After GO, repeat creation
without dry_run and use the new real IDs; never reuse synthetic IDs in live requests.

Use the TokPortal MCP tools. Build my weekly digest: get_analytics_dashboard for the last 7 days,
get_analytics_series (views, day, gained) for the same window, top 5 videos across accounts via
list_account_video_analytics, and any list_account_bans since 7 days ago. Output a short markdown report.
```

Use `maxSteps`/`stopWhen` so the model can chain several `tokportal_*` calls in one `generateText` run.

**REST equivalent** (write requests below are simulations; GET requests read existing real data)

```bash
curl "https://app.tokportal.com/api/ext/analytics?platform=tiktok&country=US&from=2026-08-01&to=2026-08-31" -H "X-API-Key: sk_..."

curl "https://app.tokportal.com/api/ext/analytics/series?metric=views&granularity=day&mode=gained&from=2026-08-01&to=2026-08-31" -H "X-API-Key: sk_..."

curl "https://app.tokportal.com/api/ext/accounts/ACCOUNT_ID/analytics/videos?sort_by=views&sort_order=desc&per_page=10" -H "X-API-Key: sk_..."

curl "https://app.tokportal.com/api/ext/analytics/export/videos?platform=tiktok&from=2026-08-01&to=2026-08-31" -H "X-API-Key: sk_..." -o videos.csv
```

## Key parameters

| Parameter                      | Values                                        | Notes                                        |
| ------------------------------ | --------------------------------------------- | -------------------------------------------- |
| `from / to`                    | YYYY-MM-DD                                    | Date window on dashboard, series, exports.   |
| `platform / country / account` | repeatable                                    | Filters on dashboard and exports.            |
| `metric`                       | views · likes · comments · shares · followers | get\_analytics\_series.                      |
| `granularity / mode`           | day · week / cumulative · gained · snapshot   | gained+day for daily deltas.                 |
| `sort_by / sort_order`         | e.g. views · desc                             | list\_account\_video\_analytics.             |
| `q`                            | text                                          | Caption search in export\_analytics\_videos. |

Full schemas: [OpenAPI reference](https://developers.tokportal.com/api-reference) · [openapi.json](https://developers.tokportal.com/openapi.json).

## Example configurations

**Dashboard call (query)**

```json
{"platform":["tiktok","instagram"],"country":["US"],"from":"2026-08-01","to":"2026-08-31"}
```

**Series call (query)**

```json
{"metric":"followers","granularity":"day","mode":"gained","account":"ACCOUNT_UUID","from":"2026-08-01","to":"2026-08-31"}
```

**Report request**

```json
{"title":"August recap","from":"2026-08-01","to":"2026-08-31","platforms":["tiktok"],"countries":["US","GB"]}
```

## Credits

Analytics reads are free and count only against the 120 requests/minute rate limit. Refreshes are throttled per account (`can_refresh_account_analytics`). See [Credits & Pricing](https://developers.tokportal.com/credits) and [Analytics API](https://developers.tokportal.com/analytics).

## Why not the official API

Official insight APIs (TikTok Display/Research, Instagram Graph insights) require each account to be yours, authorized via OAuth, and — on Instagram — a professional account; aggregating 50 accounts means 50 tokens and 50 refresh cycles. TokPortal already operates the accounts and exposes one aggregated, filterable analytics surface.

As of August 2026 the first-party routes look like this. TikTok's Content Posting API (Direct Post) requires each account owner to authorize your app with the `video.publish` scope, limits every user access token to 6 requests per minute, keeps all posts from unaudited apps in private viewing mode until TikTok audits the app, and enforces an unpublished daily post cap per user (`spam_risk_too_many_posts`) that integrators commonly report at roughly 15–25 posts per account per day. Meta's Instagram Content Publishing API allows 100 API-published posts per professional account in a 24-hour moving window and only for accounts you own and connect via OAuth. Neither creates accounts, warms them, or reports third-party bans. TokPortal is human-operated infrastructure: accounts created and run by managers in the target country, one `X-API-Key` for all of them, dated slots (max 3 per day per bundle) instead of per-account tokens.

Sources: [TikTok Content Posting API – Direct Post](https://developers.tiktok.com/doc/content-posting-api-reference-direct-post), [TikTok Content Posting API – Get started](https://developers.tiktok.com/doc/content-posting-api-get-started), [Instagram Platform – Content Publishing](https://developers.facebook.com/docs/instagram-platform/content-publishing).

## FAQ

### How fresh are the numbers?

`get_analytics_contract` states the freshness rules; most accounts refresh on a schedule and `refresh_account_analytics` can force one when `can_refresh_account_analytics` says so.

### Can I get lifetime views per video?

`list_account_video_analytics` and `get_video_analytics` return the per-video counters as collected; series use `mode=cumulative` for running totals or `gained` for deltas.

### How do I build a daily digest?

Schedule the agent (cron, n8n, Copilot Studio trigger…) to call the dashboard for yesterday, the top videos, `list_account_bans?since=yesterday`, and post the summary.

### Is there raw data?

`list_analytics_account_raw_snapshots` and `list_analytics_post_raw_snapshots` expose the underlying snapshots for audits.

## Related

- [Analytics API](https://developers.tokportal.com/analytics)
- [Saved accounts](https://developers.tokportal.com/saved-accounts)
- [Agency multi-client](https://developers.tokportal.com/use-cases/industry/agency-multi-client-management)
- [Webhooks](https://developers.tokportal.com/webhooks)
- [MCP server](https://developers.tokportal.com/mcp)

## Also works with

- [Pull analytics across all accounts with Windsurf](https://developers.tokportal.com/agents/windsurf/analytics-multi-account)
- [Pull analytics across all accounts with Cline](https://developers.tokportal.com/agents/cline/analytics-multi-account)
- [Pull analytics across all accounts with OpenClaw](https://developers.tokportal.com/agents/openclaw/analytics-multi-account)
- [Pull analytics across all accounts with Hermes Agent](https://developers.tokportal.com/agents/hermes-agent/analytics-multi-account)
- [Pull analytics across all accounts with Gemini CLI](https://developers.tokportal.com/agents/gemini-cli/analytics-multi-account)
- [Pull analytics across all accounts with Goose](https://developers.tokportal.com/agents/goose/analytics-multi-account)

[All 25 agents for "Pull analytics across all accounts"](https://developers.tokportal.com/agents/for/analytics-multi-account)

## Other jobs with Vercel AI SDK

- [Create TikTok accounts with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/create-tiktok-accounts)
- [Post 100 TikTok videos a day with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/post-100-videos-a-day)
- [Run US TikTok accounts from abroad with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/us-tiktok-accounts-from-abroad)
- [Warm TikTok & Instagram accounts with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/warm-accounts)
- [Run a faceless TikTok channel with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/faceless-channel)
- [Seed UGC across many accounts with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/ugc-seeding)
- [Seed a music sound on TikTok with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/music-sound-seeding)
- [Launch an app with persona accounts with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/app-persona-launch)
- [Run multi-client agency operations with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/agency-multi-client)
- [Get ban alerts via webhooks with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/ban-webhooks)
- [Create Instagram accounts with Vercel AI SDK](https://developers.tokportal.com/agents/vercel-ai-sdk/create-instagram-accounts)
