# TypeScript and JavaScript SDK

Package: **@progress/observability**

## Overview

The TypeScript/JavaScript SDK instruments AI agents and LLM applications running on Node.js. It supports both ESM and CommonJS module systems.

Use this SDK when your agent is built with TypeScript or JavaScript and uses frameworks like LangChain.js, Vercel AI SDK, OpenAI Node, Anthropic, or any of the other supported providers.

Core capabilities:

* Automatic instrumentation of LLM providers and agent frameworks
* Manual instrumentation with `@task`, `@workflow`, `@agent`, `@tool` decorators and `wrapFunctionWithSpan()`
* Runtime span enrichment with attributes and tags through `passSpan`
* Tag propagation with `propagateAttributes()`
* ESM loader hooks for transparent module patching
* Content tracing control

## Installation

```bash
npm install @progress/observability
```

## Initialization

Initialization depends on your module system.

### ESM / TypeScript — Bootstrap File (Recommended)

Create a separate bootstrap file that initializes instrumentation before your app loads:

```typescript
// bootstrap.ts — ESM instrumentation bootstrap
import '@progress/observability/register/hooks';
import dotenv from 'dotenv';
dotenv.config();

import { Observability } from '@progress/observability';

await Observability.instrument({
    appName: 'my-ai-agent',
    apiKey: process.env.OBSERVABILITY_API_KEY
});

// Load your main app after instrumentation is ready
await import('./src/app.ts');
```

Run with: `tsx bootstrap.ts`

### ESM / TypeScript — Inline (No Bootstrap File)

Initialize with dynamic imports at the top of your main entry point:

```typescript
// src/app.ts — ESM without bootstrap file
import '@progress/observability/register/hooks';
const { Observability } = await import('@progress/observability');
import dotenv from 'dotenv';
dotenv.config();

await Observability.instrument({
    appName: 'my-ai-agent',
    apiKey: process.env.OBSERVABILITY_API_KEY
});

// Your application code here
```

### CommonJS / Synchronous CommonJS

```typescript
// bootstrap.ts — CommonJS
const { Observability } = require('@progress/observability');
require('dotenv').config();

async function main() {
    await Observability.instrument({
        appName: 'my-ai-agent',
        apiKey: process.env.OBSERVABILITY_API_KEY
    });

    require('./src/app'); // load the app only after instrument()
}

main();
```

CommonJS has no top-level await, so wrap initialization in an async entry point. Do not import the `register/hooks` module — it intercepts ESM resolution only.

> When using ESM with LangChain, use dynamic imports for LangChain modules after calling `instrument()`.

## Configuration

Full configuration example with all options:

```typescript
import { Observability, ObservabilityInstruments } from '@progress/observability';

await Observability.instrument({
    appName: 'my-ai-agent',
    apiKey: process.env.OBSERVABILITY_API_KEY,
    endpoint: 'https://collector.observability.progress.com:443',  // default
    debug: false,
    traceContent: true,           // set false to exclude prompts/responses
    disableBatch: true,           // send traces immediately (default)
    instruments: new Set([        // only enable specific instruments
        ObservabilityInstruments.OPENAI,
        ObservabilityInstruments.LANGCHAIN
    ]),
    additionalTags: ['production', 'release:2.4.1']
});
```

### Parameters

| Parameter          | Required | Default                                                                                           | Description                               |
| ------------------ | -------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| appName            | No       | process.argv\[1]                                                                                  | Application name shown in platform        |
| apiKey             | Yes\*    | undefined                                                                                         | Your API key (\* or set env var)          |
| endpoint           | No       | [https://collector.observability.progress.com:443](https://collector.observability.progress.com/) | Collector endpoint URL                    |
| debug              | No       | false                                                                                             | Enable debug logging                      |
| traceContent       | No       | true                                                                                              | Include prompts and completions in traces |
| disableBatch       | No       | true                                                                                              | Send traces immediately (no batching)     |
| instruments        | No       | undefined (all)                                                                                   | Set of instruments to enable              |
| blockInstruments   | No       | undefined                                                                                         | Set of instruments to disable             |
| additionalTags     | No       | undefined                                                                                         | Global tags applied to all spans          |
| resourceAttributes | No       | undefined                                                                                         | Custom resource attributes                |
| headers            | No       | undefined                                                                                         | Custom headers for exporter               |

### Environment Variables

```bash
# Set these environment variables instead of passing them to instrument()
export OBSERVABILITY_APP_NAME="my-ai-agent"
export OBSERVABILITY_API_KEY="<your-api-key>"
export OBSERVABILITY_ENDPOINT="https://collector.observability.progress.com:443"
export OBSERVABILITY_TRACE_CONTENT="true"
```

| Variable                    | Overrides                    |
| --------------------------- | ---------------------------- |
| OBSERVABILITY_APP_NAME      | appName                      |
| OBSERVABILITY_API_KEY       | apiKey                       |
| OBSERVABILITY_ENDPOINT      | endpoint                     |
| OBSERVABILITY_TRACE_CONTENT | traceContent (true or false) |

## Decorators

The TypeScript SDK provides the same four decorators as the Python SDK. In TypeScript, decorators are applied to class methods:

| Decorator | Span Kind | Use For                                 |
| --------- | --------- | --------------------------------------- |
| @task     | task      | A discrete unit of work                 |
| @workflow | workflow  | A multi-step orchestration              |
| @agent    | agent     | An AI agent entry point                 |
| @tool     | tool      | A tool or function the agent can invoke |

### Examples

@agent

```typescript
import { agent } from '@progress/observability';

class SupportAgent {
    @agent({ name: 'support-agent' })
    async handleRequest(message: string) {
        // Agent logic with LLM calls, tool usage, and so on
        return response;
    }
}
```

@workflow

```typescript
import { workflow } from '@progress/observability';

class OnboardingService {
    @workflow({ name: 'onboarding-flow', version: 2 })
    async onboardCustomer(customerId: string) {
        await this.verifyIdentity(customerId);
        await this.createAccount(customerId);
        await this.sendWelcomeEmail(customerId);
    }
}
```

@tool

```typescript
import { tool } from '@progress/observability';

class SearchTools {
    @tool({ name: 'web-search' })
    async searchWeb(query: string): Promise<string> {
        // Tool implementation
        return results;
    }
}
```

### Wrapping Standalone Functions

For functions that are not class methods, use `wrapFunctionWithSpan()`:

```typescript
import { wrapFunctionWithSpan, ObservabilitySpanKind } from '@progress/observability';

// Wrap a standalone function (not a class method)
const instrumentedFetch = wrapFunctionWithSpan(
    fetchData,
    'fetch-data',
    { spanKind: ObservabilitySpanKind.TOOL, tags: ['api-call'] }
);

// Call the wrapped function — a span is created automatically
const result = await instrumentedFetch(url);
```

The wrapper keeps the parameter and return types of the original function. It forwards all arguments, ends the span when the function completes, awaits async functions, and rethrows any exception.

#### Options

| Option   | Required | Default                      | Description                                                                                              |
| -------- | -------- | ---------------------------- | -------------------------------------------------------------------------------------------------------- |
| spanKind | No       | `ObservabilitySpanKind.TASK` | The kind of span to create, for example `ObservabilitySpanKind.TOOL` or `ObservabilitySpanKind.WORKFLOW` |
| tags     | No       | undefined                    | Static tags to add to the span when it is created                                                        |
| passSpan | No       | false                        | Passes the created span to the wrapped function as its first argument                                    |

### Enriching a Span at Runtime

The static `tags` option cannot hold values that are only known while the function runs, such as the number of matching products or how many are in stock. To add this data, set `passSpan: true`. The SDK then passes the span it created as the first argument of your function, so you do not need to call `trace.getActiveSpan()` or cast types.

```typescript
import { wrapFunctionWithSpan, ObservabilitySpanKind } from '@progress/observability';

const searchProducts = wrapFunctionWithSpan(
    async (span, query: string) => {
        const products = await getProducts(query);
        const inStockCount = products.filter(product => product.inStock).length;

        span.setAttribute('search_query', query);
        span.setAttributes({ products_found: products.length, in_stock_count: inStockCount });
        span.addTags([products.length > 0 ? 'has-results' : 'no-results', `count:${products.length}`]);

        return products;
    },
    'search-products',
    { spanKind: ObservabilitySpanKind.TOOL, passSpan: true }
);

// Pass only your own arguments — the span is injected automatically
const products = await searchProducts('wireless headphones');
```

TypeScript infers the injected `span` automatically. The returned function accepts only your original arguments and preserves their types and the return type.

When `passSpan` is `false` or omitted, the function receives only the arguments you pass, as in the previous example.

#### Inline Invocation

To instrument inline logic without declaring a separate wrapper variable, invoke the wrapped function immediately:

```typescript
const products = await wrapFunctionWithSpan(
    async (span, query: string) => {
        const results = await getProducts(query);
        span.setAttribute('results_count', results.length);
        return results;
    },
    'fetch-products',
    { spanKind: ObservabilitySpanKind.TOOL, passSpan: true }
)('wireless headphones');
```

#### Span Methods

| Method                      | Description                                            |
| --------------------------- | ------------------------------------------------------ |
| `setAttribute(key, value)`  | Sets a single key-value attribute on the span          |
| `setAttributes(attributes)` | Sets multiple key-value attributes on the span at once |
| `addTags(tags)`             | Adds one or more tags to the span                      |

`addTags()` follows these rules:

* Added tags merge with the tags that the span already has, such as global, scoped, and `wrapFunctionWithSpan()` tags. Existing tags are preserved.
* Each tag is kept only once, even if you add it several times.
* Invalid tags are dropped and the SDK logs a warning.
* Passing an empty list leaves the span tags unchanged.
* Tags apply only to the current span. Child spans do not inherit them automatically. To apply tags to all spans in a scope, use `propagateAttributes()`, described in the [Tags](https://www.telerik.com/ai-observability-platform/documentation/sdk/typescript#tags) section.

## Tags

Tags work the same way as in the Python SDK. Three levels are available, plus runtime tags that the TypeScript SDK adds to a single span:

### 1. Global Tags

```typescript
await Observability.instrument({
    appName: 'my-ai-agent',
    apiKey: process.env.OBSERVABILITY_API_KEY,
    additionalTags: ['production', 'release:2.4.1']
});
```

### 2. Scoped Tags

```typescript
import { propagateAttributes } from '@progress/observability';

propagateAttributes(['tenant:acme', 'experiment-v2'], () => {
    // All spans created here inherit these tags
    myAgentFunction();
});

// Nesting is supported — tags accumulate
propagateAttributes(['outer-tag'], () => {
    propagateAttributes(['inner-tag'], () => {
        doWork(); // span gets both "outer-tag" and "inner-tag"
    });
});
```

### 3. Decorator Tags

```typescript
import { task } from '@progress/observability';

class MyService {
    @task({ tags: ['cohort-a'] })
    async myTask() {
        // ...
    }
}
```

### 4. Runtime Tags

Add tags that are only known while a function runs with `span.addTags()`. This requires wrapping the function with `wrapFunctionWithSpan()` and `passSpan: true`. These tags apply only to the current span. For details, see [Enriching a Span at Runtime](https://www.telerik.com/ai-observability-platform/documentation/sdk/typescript#enriching-a-span-at-runtime).

## Supported Instruments

### Currently Instrumented

| Category         | Instruments                                                |
| ---------------- | ---------------------------------------------------------- |
| LLM Providers    | `OPENAI`, `ANTHROPIC`, `COHERE`, `BEDROCK`, `AZURE_OPENAI` |
| Agent Frameworks | `LANGCHAIN`, `LLAMA_INDEX`                                 |
| Vector Databases | `PINECONE`, `CHROMA`                                       |

### Controlling Instruments

```typescript
import { Observability, ObservabilityInstruments } from '@progress/observability';

// Enable everything except Redis
await Observability.instrument({
    appName: 'my-ai-agent',
    apiKey: process.env.OBSERVABILITY_API_KEY,
    blockInstruments: new Set([ObservabilityInstruments.REDIS])
});
```

## Shutdown

Call `shutdown()` before your process exits to flush any pending telemetry:

```typescript
// Call shutdown before your process exits
try {
    await runAgent();
} finally {
    await Observability.shutdown();
}
```

`Observability.shutdown()` accepts an optional `timeoutMs` parameter. The default is 30000.

## Requirements

Node.js 18 or later (examples tested on Node 22)

ESM projects need the `register/hooks` import; CommonJS projects must not use it.

## See Also

* [Security and privacy best practices](https://www.telerik.com/ai-observability-platform/documentation/security/best-practices)
* [Understand traces, spans, and evaluations](https://www.telerik.com/ai-observability-platform/documentation/core-concepts)
* [Resolve TypeScript telemetry issues](https://www.telerik.com/ai-observability-platform/documentation/troubleshooting)
* [Connect AI clients with the MCP server](https://www.telerik.com/ai-observability-platform/documentation/mcp)
* [Get started with platform setup](https://www.telerik.com/ai-observability-platform/documentation/getting-started)
