> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://respan.ai/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://respan.ai/docs/_mcp/server.

# Codex SDK (tracing)

> Trace OpenAI Codex SDK turns with Respan including streamed turns, command execution, MCP tool calls, file changes, and structured output.

The [OpenAI Codex SDK](https://github.com/openai/codex) (`@openai/codex-sdk`) lets TypeScript applications start Codex threads and run coding-agent turns programmatically. Use `@respan/instrumentation-codex-sdk` to send Codex turn activity through the Respan tracing pipeline.

#### Set up Respan

Create an account at [platform.respan.ai](https://platform.respan.ai) and grab an [API key](https://platform.respan.ai/platform/gateway/api-keys).

Run `npx @respan/cli setup` to set up with your coding agent.

#### Use Respan Gateway

See [Codex SDK gateway setup](/docs/gateway/codex-sdk) to route Codex SDK model calls through the Respan gateway.

#### Example projects

* [TypeScript examples](https://github.com/respanai/respan-example-projects/tree/main/typescript/tracing/codex-sdk)

## Setup

#### Install packages

```bash
npm install @openai/codex-sdk @respan/respan @respan/tracing @respan/instrumentation-codex-sdk
```

#### Set environment variables

```bash
export CODEX_API_KEY="YOUR_CODEX_OR_OPENAI_API_KEY"
export RESPAN_API_KEY="YOUR_RESPAN_API_KEY"
```

#### Initialize and run

```typescript
import * as CodexSDKModule from "@openai/codex-sdk";
import { Codex } from "@openai/codex-sdk";
import { Respan } from "@respan/respan";
import { CodexSDKInstrumentor } from "@respan/instrumentation-codex-sdk";

const respan = new Respan({
  apiKey: process.env.RESPAN_API_KEY,
  baseURL: process.env.RESPAN_BASE_URL,
  appName: "codex-sdk-tracing",
  instrumentations: [
    new CodexSDKInstrumentor({
      sdkModule: CodexSDKModule,
      workflowName: "codex-sdk-tracing",
      agentName: "codex-agent",
    }),
  ],
});
await respan.initialize();

const codex = new Codex({
  apiKey: process.env.CODEX_API_KEY ?? process.env.OPENAI_API_KEY,
});

const thread = codex.startThread({
  workingDirectory: process.cwd(),
  skipGitRepoCheck: true,
  sandboxMode: "read-only",
  approvalPolicy: "never",
});

const result = await respan.withWorkflow({ name: "codex-sdk-basic-turn" }, async () =>
  await thread.run("Reply with one short sentence that explains tracing.")
);

console.log(result.finalResponse);
await respan.shutdown();
```

> **Note**
>
> Pass `sdkModule` when your app imports `@openai/codex-sdk` directly. This ensures the instrumentor patches the same SDK module instance your application uses.

#### View your trace

Open the [Traces page](https://platform.respan.ai/platform/traces) to see Codex SDK turns with agent messages, reasoning, command execution, MCP tool calls, file changes, and errors.

## Captured data

| Data              | Description                                                       |
| ----------------- | ----------------------------------------------------------------- |
| Buffered turns    | `Thread.run()` calls and final responses.                         |
| Streamed turns    | `Thread.runStreamed()` events and completed agent messages.       |
| Reasoning         | Reasoning summaries emitted by Codex.                             |
| Command execution | Shell command events and results.                                 |
| MCP tool calls    | MCP tool invocation events from Codex turns.                      |
| Web search        | Web search events when enabled in Codex options.                  |
| File changes      | File change events produced by Codex.                             |
| Structured output | Output schema usage and final structured responses.               |
| Failures          | Failed turns and stream errors with backend-visible error fields. |

## Attributes

Use Respan attributes to group Codex runs by user, thread, or workflow.

```typescript
await respan.propagateAttributes(
  {
    customer_identifier: "user_123",
    thread_identifier: "codex-thread-abc",
    metadata: {
      feature: "code-review",
      environment: "production",
    },
  },
  async () => {
    await respan.withWorkflow({ name: "codex-review" }, async () => {
      await thread.run("Review this change for correctness.");
    });
  }
);
```

| Attribute                | Type     | Description                                    |
| ------------------------ | -------- | ---------------------------------------------- |
| `customer_identifier`    | `string` | Identifies the end user in Respan analytics.   |
| `thread_identifier`      | `string` | Groups related turns into a conversation.      |
| `trace_group_identifier` | `string` | Groups related spans into a named trace group. |
| `metadata`               | `object` | Custom key-value pairs attached to spans.      |