@frontmcp/observability

中文文档
1.12.2发布于 2026/11/15Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 5638

OpenTelemetry tracing, structured JSON logging, request logs and Prometheus-format metrics for FrontMCP servers

原始使用文档
文档目录10 节
  1. Install
  2. Usage
  3. Sending spans somewhere
  4. Options
  5. Key exports
  6. Trace context over MCP
  7. Docs
  8. Related packages
  9. Contributing
  10. License

@frontmcp/observability

OpenTelemetry tracing, structured JSON logs, per-request log objects and counters for FrontMCP servers. Turn it on with @FrontMcp({ observability }): each request gets a span, and so does each tool call, resource read and prompt it serves, with no change to your tool code. It also holds the counters and the Prometheus serializer behind the /metrics endpoint that @FrontMcp({ metrics }) serves.

npm License

Install

npm install @frontmcp/observability

Requires Node.js 24 or later, and @frontmcp/sdk in the app (a peer dependency, as is @frontmcp/utils, which comes with the SDK). @opentelemetry/api is installed with the package.

The optional peers each enable one thing:

PackageEnables
@opentelemetry/sdk-trace-basePrinting spans in development, setupOTel({ exporter: 'console' }) and createTestTracer()
@opentelemetry/sdk-nodesetupOTel(), which also needs @opentelemetry/resources and @opentelemetry/semantic-conventions
@opentelemetry/exporter-trace-otlp-httpSending spans to an OpenTelemetry collector over OTLP (the OpenTelemetry protocol), such as setupOTel({ exporter: 'otlp' })
pino, winstonThe pino and winston log sinks, which write to a logger you create

Usage

import { createCounter, type RequestLog } from '@frontmcp/observability';
import { App, FrontMcp, Tool, ToolContext, z } from '@frontmcp/sdk';

const ticketsClosed = createCounter('helpdesk_tickets_closed_total', 'Tickets closed');

@Tool({ name: 'close_ticket', description: 'Close a support ticket', inputSchema: { id: z.string() } })
class CloseTicket extends ToolContext {
  async execute({ id }: { id: string }) {
    await this.telemetry.withSpan('tickets.close', async (span) => {
      span.setAttribute('ticket.id', id);
    });
    ticketsClosed.inc();
    return { id, status: 'closed' };
  }
}

@App({ id: 'help-desk', name: 'Help Desk', tools: [CloseTicket] })
class HelpDeskApp {}

@FrontMcp({
  info: { name: 'help-desk', version: '1.0.0' },
  apps: [HelpDeskApp],
  observability: {
    tracing: true,
    logging: { sinks: [{ type: 'stdout' }], redactFields: ['password', 'token', 'authorization'] },
    requestLogs: {
      onRequestComplete: (entry) => {
        const log = entry as RequestLog;
        if (log.status === 'error') console.error(log.request_id, log.error);
      },
    },
  },
  metrics: { enabled: true, auth: 'token' }, // GET /metrics, with the bearer token in FRONTMCP_METRICS_TOKEN
})
export default class Server {}
  • Spans follow each request: POST / (or your entry path), then tools/call, then tool close_ticket, with your tickets.close span inside it and a client span for each outbound this.fetch(). They carry MCP attributes such as mcp.method.name, frontmcp.tool.name and a hash of the session id, never the id itself.
  • Logs: each line of the server's log becomes one JSON object with the request's trace and request ids, sent to every sink in logging.sinks.
  • Request logs: onRequestComplete gets one object per HTTP request, with its timing, what it called, its status and error, and the log lines written during it.
  • Metrics: /metrics serves process gauges (memory, CPU, event-loop lag) and every counter, in the Prometheus text format, or JSON with format: 'json'.

@FrontMcp({ observability: true }) turns on tracing alone. Without the package installed, a server with observability starts anyway and logs one warning; a server with metrics.enabled doesn't start.

Sending spans somewhere

The plugin records spans through OpenTelemetry's global tracer provider, and FrontMCP doesn't register one for you (in development it prints each span to the console). Register a provider before the server handles requests. setupOTel() does it with OpenTelemetry's Node SDK:

import { setupOTel } from '@frontmcp/observability';

const shutdown = setupOTel({ serviceName: 'help-desk', exporter: 'otlp', endpoint: 'http://localhost:4318' });

exporter is 'console' (the default) or 'otlp', which sends to endpoint plus /v1/traces. endpoint defaults to OTEL_EXPORTER_OTLP_ENDPOINT, then http://localhost:4318, and serviceName to OTEL_SERVICE_NAME, then 'frontmcp-server'. Call the function it returns to flush and stop the provider. Any other OpenTelemetry setup that registers a global tracer provider works too.

Options

OptionTypeDefaultDescription
tracingboolean | TracingOptionstrueSpans for requests and calls, and this.telemetry in tools, resources and prompts
loggingboolean | { sinks, redactFields, includeStacks, staticFields }falseStructured log entries, sent to sinks. Without sinks (logging: true included), one JSON object per line on stdout (stderr over stdio; the console in a browser)
requestLogsboolean | { maxEntries, includeSummaries, onRequestComplete }falseOne object per HTTP request, passed to onRequestComplete. includeSummaries: true adds input_summary and output_summary: argument names, result keys, content types and sizes, never values

TracingOptions turns span groups on or off: httpSpans, executionSpans, fetchSpans, transportSpans, authSpans, oauthSpans, elicitationSpans, flowStageEvents and startupReport default to true, and hookSpans (a span for each hook, verbose) to false. authSpans gives each HTTP request an auth session:verify span, with frontmcp.auth.result (authorized, anonymous, unauthorized, forbidden or error).

The log sinks are { type: 'stdout', pretty? } (one JSON object per line), { type: 'console' } (a readable line), { type: 'callback', fn }, { type: 'otlp', endpoint?, headers?, batchSize?, flushIntervalMs?, serviceName? }, { type: 'pino', logger } and { type: 'winston', logger }.

@FrontMcp({ observability }) registers ObservabilityPlugin for you. You can register ObservabilityPlugin.init(options) in plugins yourself instead, but observability also connects the logging sinks to the server's logger, which the plugin alone doesn't. Use one or the other: a server that sets observability and also lists ObservabilityPlugin in @FrontMcp({ plugins }) fails at startup with PluginConfiguredTwiceError (code PLUGIN_CONFIGURED_TWICE).

Key exports

ExportPurpose
ObservabilityPluginThe plugin that observability loads
setupOTelRegister a tracer provider through OpenTelemetry's Node SDK
createCounter, getMetricSnapshot, getCounterTotal, resetMetricSnapshotCounters for /metrics (and a global OpenTelemetry meter, if you register one), and reading them in tests
renderPrometheusExposition(counters, gauges?), renderJsonExposition, PROMETHEUS_CONTENT_TYPESerialize a counter snapshot for an endpoint of your own
ProcessStatsCollectorProcess gauges: CPU, memory, uptime, event-loop lag, active handles, open file descriptors
StructuredLogTransport, createSinks, StdoutSink, ConsoleSink, CallbackSink, OtlpSink, PinoSink, WinstonSinkStructured logging building blocks
McpAttributes, FrontMcpAttributes, RpcAttributes, HttpAttributes, EnduserAttributesSpan attribute names
FrontMcpPropagator, withSpan, startSpan, startToolSpan, ...Lower-level span helpers
createTestTracer, getFinishedSpans, assertSpanExists, assertSpanAttribute, findSpanCollect spans in memory and check them in a test

Trace context over MCP

On protocol revision 2026-07-28, a client may send traceparent, tracestate and baggage in a request's _meta, and FrontMCP copies them to the result's _meta. To put the server's spans in the client's trace, send the W3C traceparent HTTP header. See protocol versions.

Docs

Contributing

Source: libs/observability. Issues and pull requests are welcome; see CONTRIBUTING.md.

License

Apache-2.0. See LICENSE.

版本与发布记录

@frontmcp/observability 共发布 84 个版本,首次发布于 2026/04/06;过去 12 个月发布了 84 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.12.2latest2026/11/151 天前
1.12.12026/11/132 天前
1.12.02026/11/114 天前
1.12.0-rc.1rc2026/11/114 天前
1.11.32026/11/106 天前
1.11.22026/11/096 天前

其他发布通道:beta → 1.1.2-beta.1,rc → 1.12.0-rc.1。

关于 @frontmcp/observability 的常见问题

@frontmcp/observability 是什么?

OpenTelemetry tracing, structured JSON logging, request logs and Prometheus-format metrics for FrontMCP servers

如何安装 @frontmcp/observability?

在项目目录运行 npm install @frontmcp/observability,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@frontmcp/sdk(1.12.2)、@frontmcp/utils(1.12.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@frontmcp/observability 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@frontmcp/observability 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@frontmcp/observability 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@frontmcp/observability 可以商用吗?

@frontmcp/observability 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@frontmcp/observability 的下载量有多少?

根据 npm 官方下载统计,@frontmcp/observability 在 2026/10/16 – 2026/11/14 这 30 天内被下载 5,638 次,日均约 188 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@frontmcp/observability 还在维护吗?

最新版本 1.12.2 发布于 2026/11/15(1 天前);至今共发布 84 个版本,其中过去 12 个月发布了 84 个;首次发布于 2026/04/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。