> For the complete documentation index, see [llms.txt](https://docs.mediafier.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mediafier.ai/connect/typescript-sdk.md).

# TypeScript SDK

A typed client for calling Mediafier from Node and TypeScript: tools, retries, job polling, structured errors.

> **A typed client for calling Mediafier from Node and TypeScript.** `@mediafier/sdk` wraps the same gateway every other access path uses — with typed requests, automatic retries, long-running-job polling, and structured errors.

> The SDK is TypeScript-first. There is no Python SDK today.

***

## Install

```bash
npm install @mediafier/sdk
```

***

## Authenticate

The SDK presents an access token as the bearer. Obtain it by exchanging your Agent Credential (see below), and read it from the environment so it never appears in source — see [Authentication & Agent Credentials](/connect/authentication.md):

```ts
const bearerToken = process.env.MEDIAFIER_TOKEN!;
```

You pass the token (and an optional gateway URL) to each call via the `opts` argument. Organization context is derived from the token server-side — you never set a tenant header.

***

## Call a tool

The transport layer speaks MCP JSON-RPC. For a one-shot call that initializes a session and calls a tool in one step, use `callMcpInitialized`:

```ts
import { callMcpInitialized } from "@mediafier/sdk";

const result = await callMcpInitialized(
  { method: "tools/list" },
  { gatewayUrl: "https://mcp.mediafier.ai", bearerToken },
);
```

> **`gatewayUrl` is the gateway base URL — without `/mcp`.** The SDK appends the MCP path for you (`/mcp`, or `/mcp/{server-slug}` when you set `serverSlug`). This differs from a raw HTTP client, which POSTs to the full `https://mcp.mediafier.ai/mcp` ingress directly.

Lower-level building blocks are also exported: `initializeSession` (open a session and capture its id), `callMcp` (a single JSON-RPC call on an existing session), and `extractLedgerMeta` (read billing/trace metadata off a result). Protocol-version negotiation is handled for you; the supported versions are exported as `SUPPORTED_PROTOCOL_VERSIONS` / `DEFAULT_NEGOTIATED_VERSION` with an `isSupportedProtocolVersion` guard. `makeSdkTraceId` generates a client-side `X-Trace-Id` you can correlate against the `trace_id` the gateway returns.

***

## Retries

Transient failures (rate limits, gateway 5xx, transport hiccups, dispatch timeouts) are safe to retry with backoff. Wrap any call with `withRetry`, or test a failure yourself with `isRetryable`:

```ts
import { withRetry, callMcpInitialized } from "@mediafier/sdk";

const result = await withRetry(() =>
  callMcpInitialized(
    { method: "tools/call", params: { name: "<TOOL_NAME>", arguments: {} } },
    { gatewayUrl: "https://mcp.mediafier.ai", bearerToken },
  ),
);
```

***

## Long-running jobs

Some tools run long and return a job you poll until it finishes. `pollUntilTerminal` is a generic poller; `isTerminal` tests a single status. A job moves through `running` and settles on one of `succeeded`, `failed`, `cancelled`, or `timed_out`:

```ts
import { pollUntilTerminal } from "@mediafier/sdk";

const outcome = await pollUntilTerminal(jobId, {
  gatewayUrl: "https://mcp.mediafier.ai",
  bearerToken,
});
```

`pollUntilTerminal` is generic — check whether a specific tool returns a pollable job before wiring it.

***

## Errors

Gateway errors arrive as structured envelopes. Project them into typed exceptions with `GovernedSDKError` and its helpers:

```ts
import { fromMcpResult, GovernedSDKError } from "@mediafier/sdk";

try {
  const result = await callMcpInitialized(req, opts);
  fromMcpResult(result); // throws GovernedSDKError on a failure envelope
} catch (err) {
  if (err instanceof GovernedSDKError) {
    console.error(err.code, err.data?.reason, err.traceId);
  }
}
```

* `GovernedSDKError` — carries the error `code`, the envelope `data` (including `data.reason`), and the `traceId` for support correlation.
* `tryParseGovernedError` — parse an envelope without throwing.
* `fromMcpResult` / `fromRestResult` — turn a failed result into a thrown `GovernedSDKError`.
* `assertOk` — throw unless a result succeeded.

***

## REST control plane

Beyond tool execution, the SDK wraps the REST control plane for managing keys, secrets, and server deployment. Tool execution itself always goes through the gateway transport above — there is no REST shim for `/mcp`.

| Area              | Functions                                                                                                     |
| ----------------- | ------------------------------------------------------------------------------------------------------------- |
| API keys          | `createAgentKey`, `listAgentKeys`, `getAgentKey`, `regenerateAgentKey`, `revokeAgentKey`, `ackAgentKeyReveal` |
| Account secrets   | `createAccountSecret`, `listAccountSecrets`, `deleteAccountSecret`, `testAccountSecret`                       |
| Stored secrets    | `manageSecret`, `checkSecretStatus`                                                                           |
| Server deployment | `deployMcp`                                                                                                   |
| Low-level         | `restCall`                                                                                                    |

***

## Export reference

Every value exported from `@mediafier/sdk`:

* **Transport** — `callMcp`, `callMcpInitialized`, `initializeSession`, `extractLedgerMeta`, `makeSdkTraceId`, `DEFAULT_CLIENT_INFO`, `SUPPORTED_PROTOCOL_VERSIONS`, `DEFAULT_NEGOTIATED_VERSION`, `isSupportedProtocolVersion`
* **Retries** — `withRetry`, `isRetryable`
* **Jobs** — `pollUntilTerminal`, `isTerminal`
* **Errors** — `GovernedSDKError`, `tryParseGovernedError`, `fromMcpResult`, `fromRestResult`, `assertOk`
* **REST** — `restCall`, `deployMcp`, `manageSecret`, `checkSecretStatus`, `createAgentKey`, `listAgentKeys`, `getAgentKey`, `revokeAgentKey`, `regenerateAgentKey`, `ackAgentKeyReveal`, `createAccountSecret`, `listAccountSecrets`, `deleteAccountSecret`, `testAccountSecret`

***

## Next steps

* [Getting Started](/connect/getting-started.md) — install, connect, first call.
* [Authentication & Agent Credentials](/connect/authentication.md) — keys and scopes.
* [CLI](/connect/cli-reference.md) — the same capabilities from a terminal.
