Token导航 LogoToken导航TokenDH.com
Mux Node SDK logo
开发工具未说明官方级别未说明来源级核验

Mux Node SDK

MCP Server

Mux TypeScript API库提供了从服务器端TypeScript或JavaScript访问Mux REST API的便捷方式。

工具数

0

提示词数

0

GitHub Stars

179

资源数

0
视频处理JavaScriptCursorAPI集成CursorVS Code

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

muxinc

提供方

muxinc

最后核验

2026/5/17 20:23

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

Mux TypeScript API库

)](https://npmjs.org/package/@mux/mux-node)

该库提供了从服务器端TypeScript或JavaScript对Mux REST API的方便访问。

可以在上找到REST API文档 docs.mux.com。此库的完整API可在中找到 api.md.

注意:从mux-node-sdk的v14开始,我们更改了sdk的一些内部工作方式。你可以阅读更多关于这个的信息 这里.

MCP服务器

使用Mux MCP服务器使人工智能助手能够与此API交互,使他们能够探索端点、提出测试请求,并使用文档帮助将此SDK集成到您的应用程序中。

![Add to Cursor](https://cursor.com/en-US/install-mcp?name=%40mux%2Fmcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBtdXgvbWNwIl0sImVudiI6eyJNVVhfVE9LRU5fSUQiOiJteSB0b2tlbiBpZCIsIk1VWF9UT0tFTl9TRUNSRVQiOiJteSBzZWNyZXQiLCJNVVhfV0VCSE9PS19TRUNSRVQiOiJNeSBXZWJob29rIFNlY3JldCIsIk1VWF9TSUdOSU5HX0tFWSI6Ik15IEp3dCBTaWduaW5nIEtleSIsIk1VWF9QUklWQVRFX0tFWSI6Ik15IEp3dCBQcml2YXRlIEtleSIsIk1VWF9BVVRIT1JJWkFUSU9OX1RPS0VOIjoibXkgYXV0aG9yaXphdGlvbiB0b2tlbiJ9fQ) ![Install in VS Code](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40mux%2Fmcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40mux%2Fmcp%22%5D%2C%22env%22%3A%7B%22MUX_TOKEN_ID%22%3A%22my%20token%20id%22%2C%22MUX_TOKEN_SECRET%22%3A%22my%20secret%22%2C%22MUX_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%2C%22MUX_SIGNING_KEY%22%3A%22My%20Jwt%20Signing%20Key%22%2C%22MUX_PRIVATE_KEY%22%3A%22My%20Jwt%20Private%20Key%22%2C%22MUX_AUTHORIZATION_TOKEN%22%3A%22my%20authorization%20token%22%7D%7D)

注意:您可能需要在MCP客户端中设置环境变量。

安装

npm install @mux/mux-node

用法

此库的完整API可在中找到 api.md.

import Mux from '@mux/mux-node';

const client = new Mux({
  tokenId: process.env['MUX_TOKEN_ID'], // This is the default and can be omitted
  tokenSecret: process.env['MUX_TOKEN_SECRET'], // This is the default and can be omitted
});

const asset = await client.video.assets.create({
  inputs: [{ url: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4' }],
  playback_policies: ['public'],
});

console.log(asset.id);

请求和响应类型

此库包含所有请求参数和响应字段的TypeScript定义。您可以这样导入和使用它们:

import Mux from '@mux/mux-node';

const client = new Mux({
  tokenId: process.env['MUX_TOKEN_ID'], // This is the default and can be omitted
  tokenSecret: process.env['MUX_TOKEN_SECRET'], // This is the default and can be omitted
});

const params: Mux.Video.AssetCreateParams = {
  inputs: [{ url: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4' }],
  playback_policies: ['public'],
};
const asset: Mux.Video.Asset = await client.video.assets.create(params);

每个方法、请求参数和响应字段的文档都可以在文档字符串中找到,并将在大多数现代编辑器中悬停显示。

JWT助手(API 参考)

您可以使用任何与JWT兼容的库,但我们在SDK中包含了一些轻量级助手,使其更容易启动和运行。

// Assuming you have your signing key specified in your environment variables:
// Signing token ID: process.env.MUX_SIGNING_KEY
// Signing token secret: process.env.MUX_PRIVATE_KEY

// Most simple request, defaults to type video and is valid for 7 days.
const token = mux.jwt.signPlaybackId('some-playback-id');
// https://stream.mux.com/some-playback-id.m3u8?token=${token}

// If you wanted to sign a thumbnail
const thumbParams = { time: 14, width: 100 };
const thumbToken = mux.jwt.signPlaybackId('some-playback-id', {
  type: 'thumbnail',
  params: thumbParams,
});
// https://image.mux.com/some-playback-id/thumbnail.jpg?token=${token}

// If you wanted to sign a gif
const gifToken = mux.jwt.signPlaybackId('some-playback-id', { type: 'gif' });
// https://image.mux.com/some-playback-id/animated.gif?token=${token}

// Here's an example for a storyboard
const storyboardToken = mux.jwt.signPlaybackId('some-playback-id', {
  type: 'storyboard',
});

// https://image.mux.com/some-playback-id/storyboard.jpg?token=${token}

// You can also use `signViewerCounts` to get a token
// used for requests to the Mux Engagement Counts API
// https://docs.mux.com/guides/see-how-many-people-are-watching
const statsToken = mux.jwt.signViewerCounts('some-live-stream-id', {
  type: 'live_stream',
});

// https://stats.mux.com/counts?token={statsToken}

一次签署多个JWT

在需要多个令牌的情况下,比如在使用Mux Player时,事情可能会很快变得难以处理。例如,

const playbackToken = await mux.jwt.signPlaybackId(id, {
  expiration: "1d",
  type: "playback"
})
const thumbnailToken = await mux.jwt.signPlaybackId(id, {
  expiration: "1d",
  type: "thumbnail",
})
const storyboardToken = await mux.jwt.signPlaybackId(id, {
  expiration: "1d",
  type: "storyboard"
})
const drmToken = await mux.jwt.signPlaybackId(id, {
  expiration: "1d",
  type: "drm_license"
})

为了简化此用例,您可以提供多种类型 signPlaybackId 以接收多个令牌。这些代币以Mux Player可以作为道具的格式提供:

// { "playback-token", "thumbnail-token", "storyboard-token", "drm-token" }
const tokens = await mux.jwt.signPlaybackId(id, {
  expiration: "1d",
  type: ["playback", "thumbnail", "storyboard", "drm_license"]
})

如果你想为单个令牌提供参数(例如,如果你想有一个缩略图 time),您可以提供 [type, typeParams] 而不是 type:

const tokens = await mux.jwt.signPlaybackId(id, {
  expiration: "1d",
  type: ["playback", ["thumbnail", { time: 2 }], "storyboard", "drm_license"]
})

解析Webhook有效载荷

为了验证给定的有效负载是否由Mux发送,并解析webhook有效负载以在您的应用程序中使用, 您可以使用 mux.webhooks.unwrap 实用方法。

此方法接受原始 body 字符串和标题列表。只要你设置了你的 webhookSecret 在 在实例化库时,适当的配置属性将自动验证所有webhook的真实性。

以下示例显示了如何使用Next.js应用程序目录API路由处理webhook:

// app/api/mux/webhooks/route.ts
import { revalidatePath } from 'next/cache';
import { headers } from 'next/headers';

import Mux from '@mux/mux-node';

const mux = new Mux({
  webhookSecret: process.env.MUX_WEBHOOK_SECRET,
});

export async function POST(request: Request) {
  const headersList = headers();
  const body = await request.text();
  const event = mux.webhooks.unwrap(body, headersList);

  switch (event.type) {
    case 'video.live_stream.active':
    case 'video.live_stream.idle':
    case 'video.live_stream.disabled':
      /**
       * `event` is now understood to be one of the following types:
       *
       *   | Mux.Webhooks.VideoLiveStreamActiveWebhookEvent
       *   | Mux.Webhooks.VideoLiveStreamIdleWebhookEvent
       *   | Mux.Webhooks.VideoLiveStreamDisabledWebhookEvent
       */
      if (event.data.id === 'MySpecialTVLiveStreamID') {
        revalidatePath('/tv');
      }
      break;
    default:
      break;
  }

  return Response.json({ message: 'ok' });
}

验证Webhook签名

正在验证Webhook签名 _可选但鼓励_。在我们的 Webhook安全指南

/*
  If the header is valid, this function will not throw an error and will not return a value.
  If the header is invalid, this function will throw one of the following errors:
    - new Error(
      "The webhook secret must either be set using the env var, MUX_WEBHOOK_SECRET, on the client class, Mux({ webhookSecret: '123' }), or passed to this function",
    );
    - new Error('Could not find a mux-signature header');
    - new Error(
      'Webhook body must be passed as the raw JSON string sent from the server (do not parse it first).',
    );
    - new Error('Unable to extract timestamp and signatures from header')
    - new Error('No v1 signatures found');
    - new Error('No signatures found matching the expected signature for payload.')
    - new Error('Webhook timestamp is too old')
*/

/*
  `body` is the raw request body. It should be a string representation of a JSON object.
  `headers` is the value in request.headers
  `secret` is the signing secret for this configured webhook. You can find that in your webhooks dashboard
          (note that this secret is different than your API Secret Key)
*/

mux.webhooks.verifySignature(body, headers, secret);

请注意,在传递有效载荷(body)时,您希望传递未解析的原始请求体,而不是解析的JSON。如果你使用express,这里有一个例子。

const Mux = require('@mux/mux-node');
const mux = new Mux();
const express = require('express');
const bodyParser = require('body-parser');

/**
 * You'll need to make sure this is externally accessible.  ngrok (https://ngrok.com/)
 * makes this really easy.
 */

const webhookSecret = process.env.WEBHOOK_SECRET;
const app = express();

app.post('/webhooks', bodyParser.raw({ type: 'application/json' }), async (req, res) => {
  try {
    // will raise an exception if the signature is invalid
    const isValidSignature = mux.webhooks.verifySignature(req.body, req.headers, webhookSecret);
    console.log('Success:', isValidSignature);
    // convert the raw req.body to JSON, which is originally Buffer (raw)
    const jsonFormattedBody = JSON.parse(req.body);
    // await doSomething();
    res.json({ received: true });
  } catch (err) {
    // On error, return the error message
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }
});

app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

处理错误

当库不能连接到API时, 或者如果API返回非成功状态码(即4xx或5xx响应), 的一个子类 APIError 将被抛出:

const liveStream = await client.video.liveStreams
  .create({ playback_policies: ['public'] })
  .catch(async (err) => {
    if (err instanceof Mux.APIError) {
      console.log(err.status); // 400
      console.log(err.name); // BadRequestError
      console.log(err.headers); // {server: 'nginx', ...}
    } else {
      throw err;
    }
  });

错误代码如下:

状态代码错误类型
400BadRequestError
401AuthenticationError
403PermissionDeniedError
404NotFoundError
422UnprocessableEntityError
429RateLimitError
>=500InternalServerError
APIConnectionError

重试

默认情况下,某些错误将自动重试2次,并具有短暂的指数回退。 连接错误(例如,由于网络连接问题),408请求超时,409冲突, 默认情况下,429速率限制和>=500内部错误都将重试。

您可以使用 maxRetries 配置或禁用此选项:

// Configure the default for all requests:
const client = new Mux({
  maxRetries: 0, // default is 2
});

// Or, configure per-request:
await client.video.assets.retrieve('t02rm...', {
  maxRetries: 5,
});

超时

默认情况下,请求在1分钟后超时。您可以使用 timeout 选项:

// Configure the default for all requests:
const client = new Mux({
  timeout: 20 * 1000, // 20 seconds (default is 1 minute)
});

// Override per-request:
await client.video.assets.retrieve('t02rm...', {
  timeout: 5 * 1000,
});

在超时时 APIConnectionTimeoutError 被抛出。

请注意,请求的超时时间为 默认情况下重试两次.

自动分页

Mux API中的列表方法已分页。 您可以使用 for await … of 遍历所有页面中的项目的语法:

async function fetchAllDeliveryReports(params) {
  const allDeliveryReports = [];
  // Automatically fetches more pages as needed.
  for await (const deliveryReport of client.video.deliveryUsage.list()) {
    allDeliveryReports.push(deliveryReport);
  }
  return allDeliveryReports;
}

或者,您可以一次请求一个页面:

let page = await client.video.deliveryUsage.list();
for (const deliveryReport of page.data) {
  console.log(deliveryReport);
}

// Convenience methods are provided for manually paginating:
while (page.hasNextPage()) {
  page = await page.getNextPage();
  // ...
}

高级用法

访问原始响应数据(例如,标头)

“生” Response 返回由 fetch() 可以通过以下方式访问 .asResponse() 方法论 APIPromise 键入所有方法都返回的值。 此方法在收到成功响应的标头后立即返回,并且不消耗响应正文,因此您可以自由编写自定义解析或流式逻辑。

您还可以使用 .withResponse() 获取原始数据的方法 Response 以及解析的数据。 不像 .asResponse() 此方法消耗正文,解析后返回。

const client = new Mux();

const response = await client.video.assets
  .create({
    inputs: [{ url: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4' }],
    playback_policies: ['public'],
  })
  .asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object

const { data: asset, response: raw } = await client.video.assets
  .create({
    inputs: [{ url: 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4' }],
    playback_policies: ['public'],
  })
  .withResponse();
console.log(raw.headers.get('X-My-Header'));
console.log(asset.id);

日志记录

\[!重要\] 所有日志消息仅用于调试。日志消息的格式和内容 可能会在发布之间发生变化。

日志级别

日志级别可以通过两种方式配置:

  1. 通过 MUX_LOG 环境变量
  2. 使用 logLevel 客户端选项(如果设置,则覆盖环境变量)
import Mux from '@mux/mux-node';

const client = new Mux({
  logLevel: 'debug', // Show all log messages
});

可用日志级别,从最详细到最不详细:

  • 'debug' -显示调试消息、信息、警告和错误
  • 'info' -显示信息消息、警告和错误
  • 'warn' -显示警告和错误(默认)
  • 'error' -仅显示错误
  • 'off' -禁用所有日志记录

'debug' 级别,记录所有HTTP请求和响应,包括标头和正文。 一些与身份验证相关的标头被编辑,但请求和响应正文中的敏感数据 可能仍然可见。

自定义记录器

默认情况下,此库登录到 globalThis.console。您还可以提供自定义记录器。

在提供自定义记录器时 logLevel 选项仍然控制发出哪些消息,消息 低于配置级别的数据将不会发送到您的记录器。

import Mux from '@mux/mux-node';
import pino from 'pino';

const logger = pino();

const client = new Mux({
  logger: logger.child({ name: 'Mux' }),
  logLevel: 'debug', // Send all messages to pino, allowing it to filter
});

提出定制/未记录的请求

键入此库是为了方便访问文档化的API。如果你需要访问无证件 端点、参数或响应属性,库仍然可以使用。

未记录的端点

要向未记录的端点发出请求,您可以使用 client.get, client.post,以及其他HTTP动词。 在发出这些请求时,客户端上的选项(如重试)将得到尊重。

await client.post('/some/path', {
  body: { some_prop: 'foo' },
  query: { some_query_arg: 'bar' },
});

未记录的请求参数

要使用未记录的参数发出请求,您可以使用 // @ts-expect-error 关于无证 参数。此库不会在运行时验证请求是否与类型匹配,因此您可以使用任何额外的值 send将按原样发送。

client.video.assets.create({
  // ...
  // @ts-expect-error baz is not yet public
  baz: 'undocumented option',
});

对于与 GET 动词,任何额外的参数都将在查询中,所有其他请求都将发送 正文中的额外参数。

如果你想显式地发送一个额外的参数,你可以用 query, body,以及 headers 请求 选项。

未记录的响应属性

要访问未记录的响应属性,您可以使用以下命令访问响应对象 // @ts-expect-error 上 或者将响应对象转换为所需类型。与请求参数一样,我们不 从API的响应中验证或删除额外的属性。

自定义获取客户端

默认情况下,此库需要一个全局 fetch 功能已定义。

如果你想使用不同的 fetch 函数,您可以对全局进行polyfill:

import fetch from 'my-fetch';

globalThis.fetch = fetch;

或者将其传递给客户:

import Mux from '@mux/mux-node';
import fetch from 'my-fetch';

const client = new Mux({ fetch });

获取选项

如果你想设置自定义 fetch 选项而不覆盖 fetch 功能,您可以提供 fetchOptions 对象在实例化客户端或发出请求时。(请求特定选项会覆盖客户端选项。)

import Mux from '@mux/mux-node';

const client = new Mux({
  fetchOptions: {
    // `RequestInit` options
  },
});

配置代理

要修改代理行为,您可以提供自定义 fetchOptions 添加特定于运行时的代理 请求选项:

节点 \[文档\]

import Mux from '@mux/mux-node';
import * as undici from 'undici';

const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
const client = new Mux({
  fetchOptions: {
    dispatcher: proxyAgent,
  },
});

包子 \[文档\]

import Mux from '@mux/mux-node';

const client = new Mux({
  fetchOptions: {
    proxy: 'http://localhost:8888',
  },
});

迪诺 \[文档\]

import Mux from 'npm:@mux/mux-node';

const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
const client = new Mux({
  fetchOptions: {
    client: httpClient,
  },
});

常见问题

语义版本控制

此套餐通常遵循 语义化版本 尽管某些向后不兼容的更改可能会作为次要版本发布:

  1. 仅影响静态类型而不破坏运行时行为的更改。
  2. 对库内部的更改,这些更改在技术上是公开的,但不是为外部使用而设计或记录的。 _(请在GitHub上发布一个问题,让我们知道您是否依赖这些内部机制。)_
  3. 我们预计在实践中不会影响绝大多数用户的变化。

我们认真对待向后兼容性,并努力确保您能够获得平稳的升级体验。

我们非常期待您的反馈;请打开一个 问题 有问题、错误或建议。

需求

支持TypeScript>=4.9。

支持以下运行时:

  • Web浏览器(最新的Chrome、Firefox、Safari、Edge等)
  • Node.js 20 LTS或更高版本(非EOL)版本。
  • Deno v1.28.0或更高版本。
  • Bun 1.0或更高版本。
  • Cloudflare员工。
  • Vercel Edge运行时。
  • Jest 28或更大 "node" 环境("jsdom" 目前不支持)。
  • Nitro v2.6或更高版本。

请注意,目前不支持React Native。

如果您对其他运行时环境感兴趣,请在GitHub上打开或投票一个问题。

贡献

贡献文档.

目录标签

目录标签

视频处理JavaScriptCursorAPI集成API库TypeScript本地部署RESTAPI

支持客户端

CursorVS Code

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

token

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明token部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP