[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69B7KPC3PWNT8JD3YZ7N9JT":3,"skill-same:01M69B7KPC3PWNT8JD3YZ7N9JT":82},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":41,"linkOnly":42,"markdownContent":43,"markdownBody":44,"frontMatter":45,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":53,"ownerDescription":54,"updatedAt":55,"install":56,"resources":69},"01M69B7KPC3PWNT8JD3YZ7N9JT","agents-sdk-typescript-otel",null,"Use when adding, configuring, validating, or troubleshooting OpenTelemetry observability for a Microsoft 365 Agents SDK application in JavaScript or TypeScript. Trigger when the user mentions OpenTelemetry, OTel, telemetry, traces, metrics, logs, OTLP, Aspire Dashboard, Application Insights, Azure Monitor, distributed tracing, custom tracers or meters, or observing @microsoft\u002Fagents-telemetry signals.","microsoft\u002FAgents","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69B7CR81D1HSNV69XDT8KAR",1109,"MIT","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-js\u002Fskills\u002Fagents-sdk-typescript-otel\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000013","分析与可视化","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[29,30,31,32,33,34,35,9,36,37,38,39,40],"typescript","agents sdk","sdk","otel","agents sdk typescript otel","dashboard","javascript","telemetry","aspire","distributed","azure","monitor","2026-11-10 10:12:30",false,"---\nname: agents-sdk-typescript-otel\ndescription: >\n  Use when adding, configuring, validating, or troubleshooting OpenTelemetry\n  observability for a Microsoft 365 Agents SDK application in JavaScript or\n  TypeScript. Trigger when the user mentions OpenTelemetry, OTel, telemetry,\n  traces, metrics, logs, OTLP, Aspire Dashboard, Application Insights, Azure\n  Monitor, distributed tracing, custom tracers or meters, or observing\n  @microsoft\u002Fagents-telemetry signals.\n---\n\n# OpenTelemetry for Agents SDK (JavaScript\u002FTypeScript)\n\n## Goal\n\nConfigure traces, metrics, and logs for an Agents SDK application, including\nthe SDK's built-in telemetry and a local Aspire Dashboard. Make the smallest\ncomplete change that fits the project's module system, build process, package\nmanager, and existing observability architecture.\n\n## Non-negotiable rules\n\n- Inspect the project before editing. Extend an existing OpenTelemetry SDK\n  registration instead of creating a second global provider.\n- Start the OpenTelemetry SDK before importing the Agents SDK, HTTP, Express,\n  or the application entry point. Preload instrumentation with Node's\n  `--import` or `--require` option.\n- Use a stable application-specific `service.name`.\n- Let OTLP exporters read standard environment variables. Never embed\n  collector credentials, API keys, or connection strings in source.\n- Do not force all OpenTelemetry packages to the same version. The JavaScript\n  package family intentionally mixes stable API\u002FSDK versions and `0.x`\n  exporter\u002Finstrumentation versions. Install a compatible set together and\n  preserve the lockfile.\n- Never add message text, prompts, responses, tokens, authorization headers,\n  cookies, secrets, attachment contents, user names, user IDs, conversation\n  IDs, activity IDs, or arbitrary HTTP headers to custom telemetry by default.\n- Keep custom metric attributes low-cardinality. Good dimensions include\n  route type, activity type, channel ID, operation, status, and error type.\n- Do not configure always-on sampling as a production default. Honor\n  `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`.\n- Explicitly flush telemetry during shutdown. Do not silently ignore exporter\n  or shutdown errors.\n- Aspire Dashboard anonymous mode is local-development only. Bind it to\n  loopback and never deploy that configuration.\n- Telemetry must record and rethrow application errors, not swallow them.\n\n## Workflow\n\nComplete these steps in order.\n\n### 1. Inspect the application\n\nFind:\n\n- `package.json`, the lockfile, Node engine version, and package manager.\n- Whether the project uses ESM (`\"type\": \"module\"`) or CommonJS.\n- The TypeScript output directory and current start\u002Fbuild scripts.\n- The application entry point and whether it uses `startServer()`, Express, or\n  another host.\n- Existing imports from `@opentelemetry\u002F*`,\n  `@microsoft\u002Fagents-telemetry`, or logging integrations.\n- Existing `NodeSDK`, tracer provider, meter provider, logger provider,\n  exporters, processors, instrumentations, and shutdown hooks.\n- Existing OTEL settings in `.env` templates, deployment manifests,\n  container definitions, and CI\u002FCD configuration.\n\nIf observability already exists, add the missing Agents SDK-compatible global\nproviders and keep the existing exporters and instrumentations unless the user\nrequested a change.\n\n### 2. Add a compatible package set\n\nUse the repository's package manager. For npm:\n\n```powershell\nnpm install @opentelemetry\u002Fapi @opentelemetry\u002Fapi-logs `\n  @microsoft\u002Fagents-telemetry `\n  @opentelemetry\u002Fsdk-node @opentelemetry\u002Fsdk-metrics `\n  @opentelemetry\u002Fsdk-logs @opentelemetry\u002Fsdk-trace-base `\n  @opentelemetry\u002Fexporter-trace-otlp-grpc `\n  @opentelemetry\u002Fexporter-metrics-otlp-grpc `\n  @opentelemetry\u002Fexporter-logs-otlp-grpc `\n  @opentelemetry\u002Finstrumentation-http `\n  @opentelemetry\u002Fresources @opentelemetry\u002Fsemantic-conventions\n```\n\nAdapt the command for pnpm or yarn. Install the packages in one operation so\nthe package manager can resolve compatible peers. Do not manually rewrite the\nresolved versions into one shared version number.\n\n`@microsoft\u002Fagents-telemetry` is required as a direct dependency when\napplication code imports `SpanNames` or `MetricNames`; do not rely on the\nAgents SDK's transitive copy.\n\nUse OTLP\u002FHTTP exporter packages instead of the gRPC exporters only when the\ncollector requires `http\u002Fprotobuf`.\n\n### 3. Create the preload instrumentation module\n\nCreate `src\u002Finstrumentation.ts` or the equivalent path. Adapt the default\nservice name and version:\n\n```typescript\nimport { randomUUID } from 'node:crypto'\nimport { OTLPLogExporter } from '@opentelemetry\u002Fexporter-logs-otlp-grpc'\nimport { OTLPMetricExporter } from '@opentelemetry\u002Fexporter-metrics-otlp-grpc'\nimport { OTLPTraceExporter } from '@opentelemetry\u002Fexporter-trace-otlp-grpc'\nimport { HttpInstrumentation } from '@opentelemetry\u002Finstrumentation-http'\nimport { resourceFromAttributes } from '@opentelemetry\u002Fresources'\nimport {\n  BatchLogRecordProcessor,\n  type LogRecordExporter\n} from '@opentelemetry\u002Fsdk-logs'\nimport {\n  PeriodicExportingMetricReader,\n  type PushMetricExporter\n} from '@opentelemetry\u002Fsdk-metrics'\nimport { NodeSDK } from '@opentelemetry\u002Fsdk-node'\nimport type { SpanExporter } from '@opentelemetry\u002Fsdk-trace-base'\nimport {\n  ATTR_SERVICE_INSTANCE_ID,\n  ATTR_SERVICE_NAME,\n  ATTR_SERVICE_VERSION\n} from '@opentelemetry\u002Fsemantic-conventions'\n\nconst serviceName =\n  process.env.OTEL_SERVICE_NAME ?? 'contoso-support-agent'\nconst serviceVersion =\n  process.env.npm_package_version ?? '1.0.0'\n\nconst traceExporter: SpanExporter = new OTLPTraceExporter()\nconst metricExporter: PushMetricExporter = new OTLPMetricExporter()\nconst logExporter: LogRecordExporter = new OTLPLogExporter()\n\nexport const otelSdk = new NodeSDK({\n  resource: resourceFromAttributes({\n    [ATTR_SERVICE_NAME]: serviceName,\n    [ATTR_SERVICE_VERSION]: serviceVersion,\n    [ATTR_SERVICE_INSTANCE_ID]: randomUUID()\n  }),\n  traceExporter,\n  metricReader: new PeriodicExportingMetricReader({\n    exporter: metricExporter\n  }),\n  logRecordProcessors: [\n    new BatchLogRecordProcessor(logExporter)\n  ],\n  instrumentations: [\n    new HttpInstrumentation({\n      ignoreIncomingRequestHook: request =>\n        request.url?.startsWith('\u002Fhealth') === true\n    })\n  ]\n})\n\notelSdk.start()\n\nlet shutdownStarted = false\n\nconst shutdown = async (signal: NodeJS.Signals): Promise\u003Cvoid> => {\n  if (shutdownStarted) {\n    return\n  }\n\n  shutdownStarted = true\n\n  try {\n    await otelSdk.shutdown()\n  } catch (error) {\n    console.error('Failed to shut down OpenTelemetry', error)\n    process.exitCode = 1\n  } finally {\n    process.kill(process.pid, signal)\n  }\n}\n\nprocess.once('SIGTERM', signal => {\n  void shutdown(signal)\n})\n\nprocess.once('SIGINT', signal => {\n  void shutdown(signal)\n})\n```\n\nBefore using the signal-handler example, check the application's existing\nshutdown behavior. Prefer integrating `otelSdk.shutdown()` into the existing\ngraceful shutdown path so the HTTP server, storage, and telemetry all close in\nthe correct order. Do not register duplicate signal handlers.\n\nIf the installed semantic-conventions package does not expose\n`ATTR_SERVICE_INSTANCE_ID`, use the literal stable semantic key\n`'service.instance.id'`.\n\nThe `NodeSDK` installs global trace, metric, context, propagation, and log\nproviders. Agents SDK telemetry uses those global APIs automatically; no\nAgents-specific instrumentation registration is required.\n\n### 4. Preload instrumentation before the application\n\nFor an ESM TypeScript project that compiles to `dist`:\n\n```json\n{\n  \"scripts\": {\n    \"build\": \"tsc --build\",\n    \"prestart\": \"npm run build\",\n    \"start\": \"node --env-file .env --import .\u002Fdist\u002Finstrumentation.js .\u002Fdist\u002Fagent.js\"\n  }\n}\n```\n\nFor CommonJS, use `--require`:\n\n```json\n\"start\": \"node --require .\u002Fdist\u002Finstrumentation.cjs .\u002Fdist\u002Fagent.cjs\"\n```\n\nDo not import `instrumentation.ts` from the bottom of the application entry\npoint. By then, HTTP or framework modules may already be loaded and cannot be\npatched reliably.\n\nIf a test runner, worker, background process, or alternate start script\nexecutes the agent independently, preload instrumentation there too when that\nprocess should emit telemetry.\n\n### 5. Configure OTLP\n\nFor the local Aspire Dashboard using OTLP\u002FgRPC, add non-secret defaults to the\nuncommitted `.env` and document them in `.env.example` or `env.TEMPLATE`:\n\n```dotenv\nOTEL_SERVICE_NAME=contoso-support-agent\nOTEL_EXPORTER_OTLP_ENDPOINT=http:\u002F\u002Flocalhost:4317\nOTEL_EXPORTER_OTLP_PROTOCOL=grpc\n```\n\nStandard environment variables to support:\n\n| Variable | Purpose |\n|---|---|\n| `OTEL_SERVICE_NAME` | Stable application service name |\n| `OTEL_RESOURCE_ATTRIBUTES` | Stable resource metadata |\n| `OTEL_EXPORTER_OTLP_ENDPOINT` | Base OTLP collector endpoint |\n| `OTEL_EXPORTER_OTLP_PROTOCOL` | Usually `grpc` or `http\u002Fprotobuf` |\n| `OTEL_EXPORTER_OTLP_HEADERS` | Collector authentication headers; keep secret |\n| `OTEL_TRACES_SAMPLER` | Trace sampling strategy |\n| `OTEL_TRACES_SAMPLER_ARG` | Sampling strategy argument |\n| `OTEL_METRIC_EXPORT_INTERVAL` | Metric export interval in milliseconds |\n\nUse deployment secrets for `OTEL_EXPORTER_OTLP_HEADERS` and Azure Monitor\nconnection strings. Do not commit populated `.env` files.\n\n### 6. Add custom business telemetry only when useful\n\nThe Agents SDK already emits adapter, application, turn, connector, storage,\nauthentication, authorization, proactive, dialog, and Copilot Studio signals.\nAdd custom telemetry only for application-specific operations.\n\nCreate one shared helper:\n\n```typescript\nimport { metrics, trace } from '@opentelemetry\u002Fapi'\nimport { logs, SeverityNumber } from '@opentelemetry\u002Fapi-logs'\n\nconst sourceName = 'Contoso.SupportAgent'\nconst version = process.env.npm_package_version\n\nexport const agentTracer = trace.getTracer(sourceName, version)\nexport const agentMeter = metrics.getMeter(sourceName, version)\nexport const agentLogger = logs.getLogger(sourceName, version)\n\nexport const routeExecutions = agentMeter.createCounter(\n  'agent.route.executions',\n  {\n    unit: '{execution}',\n    description: 'Number of application route executions.'\n  })\n\nexport const routeDuration = agentMeter.createHistogram(\n  'agent.route.duration',\n  {\n    unit: 'ms',\n    description: 'Application route execution duration.'\n  })\n\nexport const emitErrorLog = (\n  message: string,\n  attributes: Record\u003Cstring, string | number | boolean>\n): void => {\n  agentLogger.emit({\n    severityNumber: SeverityNumber.ERROR,\n    severityText: 'ERROR',\n    body: message,\n    attributes\n  })\n}\n```\n\nInstrument a route with bounded attributes:\n\n```typescript\nimport { SpanStatusCode } from '@opentelemetry\u002Fapi'\n\nreturn agentTracer.startActiveSpan(\n  'agent.route.execute',\n  async span => {\n    const started = performance.now()\n    let status = 'ok'\n\n    try {\n      await handleMessage(context)\n    } catch (error) {\n      status = 'error'\n      const exception =\n        error instanceof Error ? error : new Error(String(error))\n\n      span.recordException(exception)\n      span.setStatus({\n        code: SpanStatusCode.ERROR,\n        message: exception.message\n      })\n      throw error\n    } finally {\n      const attributes = {\n        'route.type': 'message',\n        status\n      }\n\n      routeExecutions.add(1, attributes)\n      routeDuration.record(performance.now() - started, attributes)\n      span.end()\n    }\n  })\n```\n\nDo not add conversation, activity, user, prompt, response, URL, or exception\nmessage values to custom metrics. Use the standard application logger or the\nOpenTelemetry Logs API for operational messages, but keep sensitive content\nout of both.\n\n### 7. Set up the Aspire Dashboard\n\nCopy `assets\u002Fstart-aspire-dashboard.ps1` from this skill into a local scripts\ndirectory and run:\n\n```powershell\n.\\start-aspire-dashboard.ps1\n```\n\nOpen `http:\u002F\u002Flocalhost:18888`. The script:\n\n- Binds the UI and OTLP ports to `127.0.0.1`.\n- Exposes OTLP\u002FgRPC on `4317` and OTLP\u002FHTTP on `4318`.\n- Enables unsecured access only for local development.\n- Pulls `mcr.microsoft.com\u002Fdotnet\u002Faspire-dashboard:latest`.\n\nDo not start a second container if `aspire-dashboard` already exists. Reuse or\nstop the existing container:\n\n```powershell\ndocker stop aspire-dashboard\n```\n\n### 8. Validate end to end\n\n1. Run the project's existing build or type-check command.\n2. Start Aspire Dashboard and confirm its container remains running.\n3. Start the agent through the script that preloads instrumentation.\n4. Send at least one message through Agents Playground or a configured\n   channel.\n   Metrics are exported periodically and can take one or more export intervals,\n   plus dashboard processing time, to appear. Wait and refresh the dashboard\n   before diagnosing missing metrics.\n5. In Aspire Dashboard, confirm:\n   - Telemetry is grouped under the application's `service.name`.\n   - Traces include `agents.adapter.process` or `agents.app.run`.\n   - Metrics include `agents.activities.received`, `agents.turn.count`, or\n     another exercised SDK operation.\n   - Direct OpenTelemetry log records appear.\n6. Stop the application normally and confirm telemetry shutdown completes.\n7. Exercise a failure path when practical and confirm the error is recorded\n   while the original error behavior remains intact.\n\nSee [references\u002Fsdk-signals.md](references\u002Fsdk-signals.md) for the canonical\nAgents SDK spans, metrics, constants, and Aspire smoke test.\n\n## Exporter choices\n\n### Aspire Dashboard or another OTLP collector\n\nUse the OTLP exporter packages matching the collector protocol. gRPC is the\ndefault for the included Aspire Dashboard setup.\n\n### Azure Monitor \u002F Application Insights\n\nWhen requested, use the current supported Azure Monitor OpenTelemetry exporter\nfor Node.js and load its connection string from a secret source. Check the\nexporter's current initialization and compatibility documentation before\nediting because Azure Monitor's JavaScript OpenTelemetry integration evolves\nindependently from the core OTel packages. Preserve OTLP only when dual export\nis intentional.\n\n### Existing application loggers\n\nOpenTelemetry does not automatically export every `console`, pino, Winston, or\nother logger record. Use a compatible instrumentation\u002Ftransport for the\nproject's logger, or emit selected structured records through\n`@opentelemetry\u002Fapi-logs`. Do not replace the application's logging framework\nsolely to add telemetry.\n\n## Troubleshooting\n\n| Symptom | Check |\n|---|---|\n| No SDK spans or metrics | `NodeSDK.start()` ran before the Agents SDK was imported |\n| HTTP spans missing | Instrumentation was preloaded before `node:http`, Express, and the application |\n| Custom telemetry missing | The tracer, meter, and logger are obtained after the global SDK starts |\n| Logs missing | A log record processor\u002Fexporter exists and the app emits through an integrated logger |\n| Dashboard empty | Endpoint is `http:\u002F\u002Flocalhost:4317`; exporter and protocol are both gRPC |\n| Traces appear but metrics do not | Metrics can take one or more `OTEL_METRIC_EXPORT_INTERVAL` periods plus dashboard processing time to appear; wait and refresh before troubleshooting |\n| OTLP protocol error | Exporter package, endpoint port, and protocol do not match |\n| Duplicate telemetry | More than one SDK\u002Fprovider or duplicate instrumentation preload exists |\n| Process hangs during shutdown | Integrate OTel shutdown with the server's existing graceful shutdown |\n| Last spans or logs are absent | Await `sdk.shutdown()` before process exit |\n| High telemetry cost | Remove high-cardinality attributes and reduce trace sampling |\n\n## Contributing\n\nIf SDK signals differ from [references\u002Fsdk-signals.md](references\u002Fsdk-signals.md),\nthe sample no longer builds, or the Aspire setup changes, draft an issue\ncontaining the module system, Node and package versions, start command,\nexpected signal, actual result, and any workaround:\nhttps:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fagents\u002Fissues\u002Fnew\n","# OpenTelemetry for Agents SDK (JavaScript\u002FTypeScript)\n\n## Goal\n\nConfigure traces, metrics, and logs for an Agents SDK application, including\nthe SDK's built-in telemetry and a local Aspire Dashboard. Make the smallest\ncomplete change that fits the project's module system, build process, package\nmanager, and existing observability architecture.\n\n## Non-negotiable rules\n\n- Inspect the project before editing. Extend an existing OpenTelemetry SDK\n  registration instead of creating a second global provider.\n- Start the OpenTelemetry SDK before importing the Agents SDK, HTTP, Express,\n  or the application entry point. Preload instrumentation with Node's\n  `--import` or `--require` option.\n- Use a stable application-specific `service.name`.\n- Let OTLP exporters read standard environment variables. Never embed\n  collector credentials, API keys, or connection strings in source.\n- Do not force all OpenTelemetry packages to the same version. The JavaScript\n  package family intentionally mixes stable API\u002FSDK versions and `0.x`\n  exporter\u002Finstrumentation versions. Install a compatible set together and\n  preserve the lockfile.\n- Never add message text, prompts, responses, tokens, authorization headers,\n  cookies, secrets, attachment contents, user names, user IDs, conversation\n  IDs, activity IDs, or arbitrary HTTP headers to custom telemetry by default.\n- Keep custom metric attributes low-cardinality. Good dimensions include\n  route type, activity type, channel ID, operation, status, and error type.\n- Do not configure always-on sampling as a production default. Honor\n  `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`.\n- Explicitly flush telemetry during shutdown. Do not silently ignore exporter\n  or shutdown errors.\n- Aspire Dashboard anonymous mode is local-development only. Bind it to\n  loopback and never deploy that configuration.\n- Telemetry must record and rethrow application errors, not swallow them.\n\n## Workflow\n\nComplete these steps in order.\n\n### 1. Inspect the application\n\nFind:\n\n- `package.json`, the lockfile, Node engine version, and package manager.\n- Whether the project uses ESM (`\"type\": \"module\"`) or CommonJS.\n- The TypeScript output directory and current start\u002Fbuild scripts.\n- The application entry point and whether it uses `startServer()`, Express, or\n  another host.\n- Existing imports from `@opentelemetry\u002F*`,\n  `@microsoft\u002Fagents-telemetry`, or logging integrations.\n- Existing `NodeSDK`, tracer provider, meter provider, logger provider,\n  exporters, processors, instrumentations, and shutdown hooks.\n- Existing OTEL settings in `.env` templates, deployment manifests,\n  container definitions, and CI\u002FCD configuration.\n\nIf observability already exists, add the missing Agents SDK-compatible global\nproviders and keep the existing exporters and instrumentations unless the user\nrequested a change.\n\n### 2. Add a compatible package set\n\nUse the repository's package manager. For npm:\n\n```powershell\nnpm install @opentelemetry\u002Fapi @opentelemetry\u002Fapi-logs `\n  @microsoft\u002Fagents-telemetry `\n  @opentelemetry\u002Fsdk-node @opentelemetry\u002Fsdk-metrics `\n  @opentelemetry\u002Fsdk-logs @opentelemetry\u002Fsdk-trace-base `\n  @opentelemetry\u002Fexporter-trace-otlp-grpc `\n  @opentelemetry\u002Fexporter-metrics-otlp-grpc `\n  @opentelemetry\u002Fexporter-logs-otlp-grpc `\n  @opentelemetry\u002Finstrumentation-http `\n  @opentelemetry\u002Fresources @opentelemetry\u002Fsemantic-conventions\n```\n\nAdapt the command for pnpm or yarn. Install the packages in one operation so\nthe package manager can resolve compatible peers. Do not manually rewrite the\nresolved versions into one shared version number.\n\n`@microsoft\u002Fagents-telemetry` is required as a direct dependency when\napplication code imports `SpanNames` or `MetricNames`; do not rely on the\nAgents SDK's transitive copy.\n\nUse OTLP\u002FHTTP exporter packages instead of the gRPC exporters only when the\ncollector requires `http\u002Fprotobuf`.\n\n### 3. Create the preload instrumentation module\n\nCreate `src\u002Finstrumentation.ts` or the equivalent path. Adapt the default\nservice name and version:\n\n```typescript\nimport { randomUUID } from 'node:crypto'\nimport { OTLPLogExporter } from '@opentelemetry\u002Fexporter-logs-otlp-grpc'\nimport { OTLPMetricExporter } from '@opentelemetry\u002Fexporter-metrics-otlp-grpc'\nimport { OTLPTraceExporter } from '@opentelemetry\u002Fexporter-trace-otlp-grpc'\nimport { HttpInstrumentation } from '@opentelemetry\u002Finstrumentation-http'\nimport { resourceFromAttributes } from '@opentelemetry\u002Fresources'\nimport {\n  BatchLogRecordProcessor,\n  type LogRecordExporter\n} from '@opentelemetry\u002Fsdk-logs'\nimport {\n  PeriodicExportingMetricReader,\n  type PushMetricExporter\n} from '@opentelemetry\u002Fsdk-metrics'\nimport { NodeSDK } from '@opentelemetry\u002Fsdk-node'\nimport type { SpanExporter } from '@opentelemetry\u002Fsdk-trace-base'\nimport {\n  ATTR_SERVICE_INSTANCE_ID,\n  ATTR_SERVICE_NAME,\n  ATTR_SERVICE_VERSION\n} from '@opentelemetry\u002Fsemantic-conventions'\n\nconst serviceName =\n  process.env.OTEL_SERVICE_NAME ?? 'contoso-support-agent'\nconst serviceVersion =\n  process.env.npm_package_version ?? '1.0.0'\n\nconst traceExporter: SpanExporter = new OTLPTraceExporter()\nconst metricExporter: PushMetricExporter = new OTLPMetricExporter()\nconst logExporter: LogRecordExporter = new OTLPLogExporter()\n\nexport const otelSdk = new NodeSDK({\n  resource: resourceFromAttributes({\n    [ATTR_SERVICE_NAME]: serviceName,\n    [ATTR_SERVICE_VERSION]: serviceVersion,\n    [ATTR_SERVICE_INSTANCE_ID]: randomUUID()\n  }),\n  traceExporter,\n  metricReader: new PeriodicExportingMetricReader({\n    exporter: metricExporter\n  }),\n  logRecordProcessors: [\n    new BatchLogRecordProcessor(logExporter)\n  ],\n  instrumentations: [\n    new HttpInstrumentation({\n      ignoreIncomingRequestHook: request =>\n        request.url?.startsWith('\u002Fhealth') === true\n    })\n  ]\n})\n\notelSdk.start()\n\nlet shutdownStarted = false\n\nconst shutdown = async (signal: NodeJS.Signals): Promise\u003Cvoid> => {\n  if (shutdownStarted) {\n    return\n  }\n\n  shutdownStarted = true\n\n  try {\n    await otelSdk.shutdown()\n  } catch (error) {\n    console.error('Failed to shut down OpenTelemetry', error)\n    process.exitCode = 1\n  } finally {\n    process.kill(process.pid, signal)\n  }\n}\n\nprocess.once('SIGTERM', signal => {\n  void shutdown(signal)\n})\n\nprocess.once('SIGINT', signal => {\n  void shutdown(signal)\n})\n```\n\nBefore using the signal-handler example, check the application's existing\nshutdown behavior. Prefer integrating `otelSdk.shutdown()` into the existing\ngraceful shutdown path so the HTTP server, storage, and telemetry all close in\nthe correct order. Do not register duplicate signal handlers.\n\nIf the installed semantic-conventions package does not expose\n`ATTR_SERVICE_INSTANCE_ID`, use the literal stable semantic key\n`'service.instance.id'`.\n\nThe `NodeSDK` installs global trace, metric, context, propagation, and log\nproviders. Agents SDK telemetry uses those global APIs automatically; no\nAgents-specific instrumentation registration is required.\n\n### 4. Preload instrumentation before the application\n\nFor an ESM TypeScript project that compiles to `dist`:\n\n```json\n{\n  \"scripts\": {\n    \"build\": \"tsc --build\",\n    \"prestart\": \"npm run build\",\n    \"start\": \"node --env-file .env --import .\u002Fdist\u002Finstrumentation.js .\u002Fdist\u002Fagent.js\"\n  }\n}\n```\n\nFor CommonJS, use `--require`:\n\n```json\n\"start\": \"node --require .\u002Fdist\u002Finstrumentation.cjs .\u002Fdist\u002Fagent.cjs\"\n```\n\nDo not import `instrumentation.ts` from the bottom of the application entry\npoint. By then, HTTP or framework modules may already be loaded and cannot be\npatched reliably.\n\nIf a test runner, worker, background process, or alternate start script\nexecutes the agent independently, preload instrumentation there too when that\nprocess should emit telemetry.\n\n### 5. Configure OTLP\n\nFor the local Aspire Dashboard using OTLP\u002FgRPC, add non-secret defaults to the\nuncommitted `.env` and document them in `.env.example` or `env.TEMPLATE`:\n\n```dotenv\nOTEL_SERVICE_NAME=contoso-support-agent\nOTEL_EXPORTER_OTLP_ENDPOINT=http:\u002F\u002Flocalhost:4317\nOTEL_EXPORTER_OTLP_PROTOCOL=grpc\n```\n\nStandard environment variables to support:\n\n| Variable | Purpose |\n|---|---|\n| `OTEL_SERVICE_NAME` | Stable application service name |\n| `OTEL_RESOURCE_ATTRIBUTES` | Stable resource metadata |\n| `OTEL_EXPORTER_OTLP_ENDPOINT` | Base OTLP collector endpoint |\n| `OTEL_EXPORTER_OTLP_PROTOCOL` | Usually `grpc` or `http\u002Fprotobuf` |\n| `OTEL_EXPORTER_OTLP_HEADERS` | Collector authentication headers; keep secret |\n| `OTEL_TRACES_SAMPLER` | Trace sampling strategy |\n| `OTEL_TRACES_SAMPLER_ARG` | Sampling strategy argument |\n| `OTEL_METRIC_EXPORT_INTERVAL` | Metric export interval in milliseconds |\n\nUse deployment secrets for `OTEL_EXPORTER_OTLP_HEADERS` and Azure Monitor\nconnection strings. Do not commit populated `.env` files.\n\n### 6. Add custom business telemetry only when useful\n\nThe Agents SDK already emits adapter, application, turn, connector, storage,\nauthentication, authorization, proactive, dialog, and Copilot Studio signals.\nAdd custom telemetry only for application-specific operations.\n\nCreate one shared helper:\n\n```typescript\nimport { metrics, trace } from '@opentelemetry\u002Fapi'\nimport { logs, SeverityNumber } from '@opentelemetry\u002Fapi-logs'\n\nconst sourceName = 'Contoso.SupportAgent'\nconst version = process.env.npm_package_version\n\nexport const agentTracer = trace.getTracer(sourceName, version)\nexport const agentMeter = metrics.getMeter(sourceName, version)\nexport const agentLogger = logs.getLogger(sourceName, version)\n\nexport const routeExecutions = agentMeter.createCounter(\n  'agent.route.executions',\n  {\n    unit: '{execution}',\n    description: 'Number of application route executions.'\n  })\n\nexport const routeDuration = agentMeter.createHistogram(\n  'agent.route.duration',\n  {\n    unit: 'ms',\n    description: 'Application route execution duration.'\n  })\n\nexport const emitErrorLog = (\n  message: string,\n  attributes: Record\u003Cstring, string | number | boolean>\n): void => {\n  agentLogger.emit({\n    severityNumber: SeverityNumber.ERROR,\n    severityText: 'ERROR',\n    body: message,\n    attributes\n  })\n}\n```\n\nInstrument a route with bounded attributes:\n\n```typescript\nimport { SpanStatusCode } from '@opentelemetry\u002Fapi'\n\nreturn agentTracer.startActiveSpan(\n  'agent.route.execute',\n  async span => {\n    const started = performance.now()\n    let status = 'ok'\n\n    try {\n      await handleMessage(context)\n    } catch (error) {\n      status = 'error'\n      const exception =\n        error instanceof Error ? error : new Error(String(error))\n\n      span.recordException(exception)\n      span.setStatus({\n        code: SpanStatusCode.ERROR,\n        message: exception.message\n      })\n      throw error\n    } finally {\n      const attributes = {\n        'route.type': 'message',\n        status\n      }\n\n      routeExecutions.add(1, attributes)\n      routeDuration.record(performance.now() - started, attributes)\n      span.end()\n    }\n  })\n```\n\nDo not add conversation, activity, user, prompt, response, URL, or exception\nmessage values to custom metrics. Use the standard application logger or the\nOpenTelemetry Logs API for operational messages, but keep sensitive content\nout of both.\n\n### 7. Set up the Aspire Dashboard\n\nCopy `assets\u002Fstart-aspire-dashboard.ps1` from this skill into a local scripts\ndirectory and run:\n\n```powershell\n.\\start-aspire-dashboard.ps1\n```\n\nOpen `http:\u002F\u002Flocalhost:18888`. The script:\n\n- Binds the UI and OTLP ports to `127.0.0.1`.\n- Exposes OTLP\u002FgRPC on `4317` and OTLP\u002FHTTP on `4318`.\n- Enables unsecured access only for local development.\n- Pulls `mcr.microsoft.com\u002Fdotnet\u002Faspire-dashboard:latest`.\n\nDo not start a second container if `aspire-dashboard` already exists. Reuse or\nstop the existing container:\n\n```powershell\ndocker stop aspire-dashboard\n```\n\n### 8. Validate end to end\n\n1. Run the project's existing build or type-check command.\n2. Start Aspire Dashboard and confirm its container remains running.\n3. Start the agent through the script that preloads instrumentation.\n4. Send at least one message through Agents Playground or a configured\n   channel.\n   Metrics are exported periodically and can take one or more export intervals,\n   plus dashboard processing time, to appear. Wait and refresh the dashboard\n   before diagnosing missing metrics.\n5. In Aspire Dashboard, confirm:\n   - Telemetry is grouped under the application's `service.name`.\n   - Traces include `agents.adapter.process` or `agents.app.run`.\n   - Metrics include `agents.activities.received`, `agents.turn.count`, or\n     another exercised SDK operation.\n   - Direct OpenTelemetry log records appear.\n6. Stop the application normally and confirm telemetry shutdown completes.\n7. Exercise a failure path when practical and confirm the error is recorded\n   while the original error behavior remains intact.\n\nSee [references\u002Fsdk-signals.md](references\u002Fsdk-signals.md) for the canonical\nAgents SDK spans, metrics, constants, and Aspire smoke test.\n\n## Exporter choices\n\n### Aspire Dashboard or another OTLP collector\n\nUse the OTLP exporter packages matching the collector protocol. gRPC is the\ndefault for the included Aspire Dashboard setup.\n\n### Azure Monitor \u002F Application Insights\n\nWhen requested, use the current supported Azure Monitor OpenTelemetry exporter\nfor Node.js and load its connection string from a secret source. Check the\nexporter's current initialization and compatibility documentation before\nediting because Azure Monitor's JavaScript OpenTelemetry integration evolves\nindependently from the core OTel packages. Preserve OTLP only when dual export\nis intentional.\n\n### Existing application loggers\n\nOpenTelemetry does not automatically export every `console`, pino, Winston, or\nother logger record. Use a compatible instrumentation\u002Ftransport for the\nproject's logger, or emit selected structured records through\n`@opentelemetry\u002Fapi-logs`. Do not replace the application's logging framework\nsolely to add telemetry.\n\n## Troubleshooting\n\n| Symptom | Check |\n|---|---|\n| No SDK spans or metrics | `NodeSDK.start()` ran before the Agents SDK was imported |\n| HTTP spans missing | Instrumentation was preloaded before `node:http`, Express, and the application |\n| Custom telemetry missing | The tracer, meter, and logger are obtained after the global SDK starts |\n| Logs missing | A log record processor\u002Fexporter exists and the app emits through an integrated logger |\n| Dashboard empty | Endpoint is `http:\u002F\u002Flocalhost:4317`; exporter and protocol are both gRPC |\n| Traces appear but metrics do not | Metrics can take one or more `OTEL_METRIC_EXPORT_INTERVAL` periods plus dashboard processing time to appear; wait and refresh before troubleshooting |\n| OTLP protocol error | Exporter package, endpoint port, and protocol do not match |\n| Duplicate telemetry | More than one SDK\u002Fprovider or duplicate instrumentation preload exists |\n| Process hangs during shutdown | Integrate OTel shutdown with the server's existing graceful shutdown |\n| Last spans or logs are absent | Await `sdk.shutdown()` before process exit |\n| High telemetry cost | Remove high-cardinality attributes and reduce trace sampling |\n\n## Contributing\n\nIf SDK signals differ from [references\u002Fsdk-signals.md](references\u002Fsdk-signals.md),\nthe sample no longer builds, or the Aspire setup changes, draft an issue\ncontaining the module system, Node and package versions, start command,\nexpected signal, actual result, and any workaround:\nhttps:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fagents\u002Fissues\u002Fnew\n",{"name":5,"description":7},"main","8171bc7e0ca3b8defd578a6bb317367c2901983f","agent-plugins\u002Fagents-for-js\u002Fskills\u002Fagents-sdk-typescript-otel",346,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents","https:\u002F\u002Faka.ms\u002Fagentsdkdocs","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-14 08:54:12",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add microsoft\u002FAgents --skill agents-sdk-typescript-otel",{"tool":62,"command":63},"bunx","bunx skills add microsoft\u002FAgents --skill agents-sdk-typescript-otel",{"tool":65,"command":66},"pnpm","pnpm dlx skills add microsoft\u002FAgents --skill agents-sdk-typescript-otel","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-js\u002Fskills\u002Fagents-sdk-typescript-otel\u002FSKILL.md",true,[70,76],{"path":71,"resourceType":72,"resourceTypeDesc":73,"sizeBytes":74,"sourceHtmlUrl":75},"assets\u002Fstart-aspire-dashboard.ps1","SCRIPT","脚本",963,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-js\u002Fskills\u002Fagents-sdk-typescript-otel\u002Fassets\u002Fstart-aspire-dashboard.ps1",{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fsdk-signals.md","REFERENCE","参考文档",5880,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-js\u002Fskills\u002Fagents-sdk-typescript-otel\u002Freferences\u002Fsdk-signals.md",[83,101,119,131,144,153],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":41},"01M6PJCYCYJQDX318SQN3EBF0E","sync-teams-samples-to-agents-sdk","CI instructions for a bounded Teams SDK to Agents SDK sample synchronization using the selected language profile.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fautomation\u002Fteams-sample-sync\u002Fskills\u002Fsync-teams-samples-to-agents-sdk\u002FSKILL.md",[],[30,31,90,91,92,93,94,95,96,97,98,99,100],"sync","teams","sync teams samples to agents sdk","ci","synchronization","instructions","profile","language","sample","for","bounded",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":41},"01M6PJCFNGCX555YERYQ459JFE","teams-sdk-to-agents-sdk-typescript-migration","Migrate a JavaScript or TypeScript application using the Microsoft Teams SDK App runtime to Microsoft 365 Agents SDK while preserving its Teams behaviors. Use for Teams SDK migrations, including automated sample synchronization; use the separate Bot Framework migration skill for botbuilder applications.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-js\u002Fskills\u002Fteams-sdk-to-agents-sdk-typescript-migration\u002FSKILL.md",[],[91,29,30,31,108,109,110,111,112,113,114,98,115,116,94,117,99,118,35,9],"agents sdk typescript","migration","teams sdk to agents sdk typescript migration","microsoft teams","applications","app","runtime","migrations","use","migrate","bot",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":128,"publishedAt":41},"01M69B8QV24JVPXH25EH77X0SZ","teams-app-manifest","Create or audit a Microsoft Teams app manifest for an existing Microsoft 365 Agents SDK application by mapping declared intent and source-code evidence to released manifest capabilities. Use when manifest.json is missing, incomplete, or must be checked against implemented Teams features. Does not configure Microsoft Entra, Azure Bot, Developer Portal, or deployment unless separately requested.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-sdk-common\u002Fskills\u002Fteams-app-manifest\u002FSKILL.md",[125],{"categoryNo":126,"categoryName":127,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师",[91,129,31,118,30,9,39,130],"teams app manifest","deployment",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":41},"01M69B8MN62NBY93YTJAQG2Y81","agents-sdk-provision","Use when provisioning Azure resources for a Microsoft Agents SDK application — including creating an Azure Bot Service resource, setting up Entra app registrations, configuring identity credentials (UserManagedIdentity, FederatedCredentials, or ClientSecret), adding a Teams channel, running Bicep deployments for SSO, or setting up OAuth user sign-in connections via az CLI. Trigger even if the user doesn't say \"provision\" — use on requests like \"set up my bot on Azure\", \"deploy my bot\", \"configure Azure for my bot\", or \"get Teams SSO working.\" Applies to all languages (dotnet, Node.js, Python).","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-sdk-common\u002Fskills\u002Fagents-sdk-provision\u002FSKILL.md",[],[30,31,138,118,139,140,9,141,142,143,39,91],"agents sdk provision","cli","python","dotnet","identity","deploy",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":41},"01M69B8HFZ45NQGWQQD483TWPB","agents-sdk-to-prod","Assess, create, harden, deploy, or review production readiness of Python Microsoft 365 Agents SDK agents and their direct hosting\u002Foperations files. Use only for Agents SDK scenarios, not unrelated application hardening.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-python\u002Fskills\u002Fagents-sdk-to-prod\u002FSKILL.md",[],[151,31,30,9,140,152,143],"agents sdk to prod","review",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":161,"publishedAt":41},"01M69B8ENJGC9NPQBZAYAN4706","agents-sdk-python-otel","Use when adding, configuring, validating, or troubleshooting OpenTelemetry observability for a Microsoft 365 Agents SDK application in Python. Trigger when the user mentions OpenTelemetry, OTel, telemetry, traces, metrics, logs, OTLP, Aspire Dashboard, Application Insights, Azure Monitor, distributed tracing, custom tracers or meters, span sampling, or observing microsoft_agents SDK signals.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-python\u002Fskills\u002Fagents-sdk-python-otel\u002FSKILL.md",[159,160],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},[30,140,32,31,162,37,39,36,9,34,38,163,40],"agents sdk python otel","aspire dashboard"]