> ## Documentation Index
> Fetch the complete documentation index at: https://docs.thecontextcompany.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Agent SDK

> Integrate The Context Company with Claude Agent SDK

## Set TCC environment variables

<Tip>Our SDKs default to using the `TCC_API_KEY` environment variable.</Tip>

```bash .env theme={null}
TCC_API_KEY="your-api-key"
```

## Instrument Claude Agent SDK

<Tabs>
  <Tab title="TypeScript">
    #### Step 1: Install dependencies

    <CodeGroup>
      ```Title pnpm theme={null}
      pnpm add @contextcompany/claude @anthropic-ai/claude-agent-sdk
      ```

      ```Title npm theme={null}
      npm i @contextcompany/claude @anthropic-ai/claude-agent-sdk
      ```

      ```Title bun theme={null}
      bun add @contextcompany/claude @anthropic-ai/claude-agent-sdk
      ```
    </CodeGroup>

    #### Step 2: Add instrumentation to your agent

    Import the `instrumentClaudeAgent` function and use it to wrap the Claude Agent SDK. This allows your app to export all agent-related traces to The Context Company.

    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query, tool, createSdkMcpServer } = instrumentClaudeAgent(claudeSDK);

    // Now use query, tool, and createSdkMcpServer as you normally would
    ```

    That's it! All your agent runs will now be automatically tracked in The Context Company.
  </Tab>

  <Tab title="Python">
    #### Step 1: Install dependencies

    <CodeGroup>
      ```Title pip theme={null}
      pip install "contextcompany[claude]"
      ```

      ```Title poetry theme={null}
      poetry add "contextcompany[claude]"
      ```
    </CodeGroup>

    #### Step 2: Add instrumentation to your agent

    Call `instrument_claude_agent()` once at startup, then use the returned object's `query()` method in place of `claude_agent_sdk.query()`. This wraps the underlying async iterator and exports all agent-related traces to The Context Company.

    ```python agent.py theme={null}
    import asyncio
    from contextcompany.claude import instrument_claude_agent, TCCConfig
    from claude_agent_sdk import ClaudeAgentOptions, AssistantMessage, TextBlock

    agent = instrument_claude_agent()

    async def main():
        async for message in agent.query(
            prompt="What is 2 + 2?",
            options=ClaudeAgentOptions(system_prompt="You are helpful."),
        ):
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(block.text)

    asyncio.run(main())
    ```

    That's it! All your agent runs will now be automatically tracked in The Context Company.
  </Tab>
</Tabs>

## Adding custom metadata

Custom metadata allows you to add additional properties to your [agent runs](/concepts#agent-runs).

This is particularly useful for tying agent runs to your own specific business logic, letting you filter and analyze agent runs by user, organization, feature, or some other dimension.

<Tabs>
  <Tab title="TypeScript">
    Custom metadata must be passed as a key-value pair to the `metadata` object within the `tcc` parameter.

    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query } = instrumentClaudeAgent(claudeSDK);

    const result = query({
      // ...
      tcc: {
        metadata: {
          // e.g. tag this agent run with a user id
          userId: "4a6b111c-b53a-4d00-a877-67185022ab9e",
        },
      },
    });
    ```
  </Tab>

  <Tab title="Python">
    Custom metadata is passed via the `metadata` field of `TCCConfig` when calling `query()`:

    ```python agent.py theme={null}
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(
            metadata={
                # e.g. tag this agent run with a user id
                "userId": "4a6b111c-b53a-4d00-a877-67185022ab9e",
            },
        ),
    ):
        ...
    ```
  </Tab>
</Tabs>

Agent runs are automatically indexed by your custom metadata fields and can be filtered directly in the dashboard.

<Note>
  The `tcc.*` namespace is reserved. Only the [reserved TCC metadata keys](/concepts#tcc-metadata-keys) (`tcc.runId`, `tcc.sessionId`, `tcc.conversational`, `tcc.agent`, `tcc.userId`, `tcc.userName`, `tcc.orgId`, `tcc.orgName`) are recognized; any other `tcc.*` keys are ignored. None of them appear in your custom metadata.
</Note>

## Adding user feedback

User feedback allows you to collect score (thumbs up & thumbs down) and text feedback (up to 2000 characters) from end users on your [agent runs](/concepts#agent-runs).

This is useful for tracking user satisfaction, identifying problematic responses, and filtering agent runs in the dashboard to focus on positive or negative feedback.

<Tabs>
  <Tab title="TypeScript">
    ### Step 1: Generate and pass a run ID

    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";
    import { randomUUID } from "crypto";

    const { query } = instrumentClaudeAgent(claudeSDK);

    // Generate a unique run ID (must be a UUID) before your agent execution
    const runId = randomUUID();

    const result = query({
      // ...
      tcc: {
        runId: runId, // Pass the run ID
      },
    });

    // Return the runId to your client
    return { result, runId };
    ```

    ### Step 2: Submit feedback from your client

    Store the `runId` on your client, then when the user provides feedback, submit it using the `submitFeedback` function.

    Both `score` and `text` are optional individually, but each request must include at least one of them:

    `score` is the thumbs rating. Use only `"thumbs_up"` or `"thumbs_down"`.

    `text` is written feedback from your user, up to 2000 characters.

    ```typescript feedback.ts theme={null}
    import { submitFeedback } from "@contextcompany/claude";

    // Submit score and/or text feedback:
    await submitFeedback({
      runId: runId, // The run ID from your agent execution
      score: "thumbs_up", // Optional thumbs rating: "thumbs_up" or "thumbs_down"
      text: "This was a helpful response!", // Optional written user feedback, up to 2000 characters
    });
    ```
  </Tab>

  <Tab title="Python">
    ### Step 1: Generate and pass a run ID

    ```python agent.py theme={null}
    import uuid
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    # Generate a unique run ID (must be a UUID) before your agent execution
    run_id = str(uuid.uuid4())

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(run_id=run_id),
    ):
        ...

    # Return the run_id to your client
    return {"run_id": run_id}
    ```

    ### Step 2: Submit feedback from your client

    Store the `run_id` on your client, then when the user provides feedback, submit it using the `submit_feedback` function.

    Both `score` and `text` are optional individually, but each request must include at least one of them:

    `score` is the thumbs rating. Use only `"thumbs_up"` or `"thumbs_down"`.

    `text` is written feedback from your user, up to 2000 characters.

    ```python feedback.py theme={null}
    from contextcompany import submit_feedback

    # Submit score and/or text feedback:
    submit_feedback(
        run_id=run_id,  # The run ID from your agent execution
        score="thumbs_up",  # Optional thumbs rating: "thumbs_up" or "thumbs_down"
        text="This was a helpful response!",  # Optional written user feedback, up to 2000 characters
    )
    ```
  </Tab>
</Tabs>

Agent runs with feedback can be filtered in the dashboard using the feedback filter.

## Tracking agent sessions

[Agent sessions](/concepts#agent-sessions) represent multiple agent runs that are grouped together. The most common use case is tracking entire conversations between a human user and an AI agent in chatbot interfaces.

<Tabs>
  <Tab title="TypeScript">
    Agent sessions can be tracked by setting a `sessionId` key within the `tcc` parameter.

    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query } = instrumentClaudeAgent(claudeSDK);

    const result = query({
      // ...
      tcc: {
        sessionId: "some-session-id", // Track agent sessions
      },
    });
    ```
  </Tab>

  <Tab title="Python">
    Agent sessions can be tracked by setting `session_id` on the `TCCConfig` passed to `query()`:

    ```python agent.py theme={null}
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(session_id="some-session-id"),
    ):
        ...
    ```
  </Tab>
</Tabs>

The value of `sessionId` should be a unique identifier for the agent session. This can be any string, but it's generally recommended to use a UUID.

Agent sessions are automatically indexed and can be filtered directly in the dashboard.

## Marking runs as conversational

A [conversational run](/concepts#conversational-runs) is an agent run that was initiated by a user. Marking a run as conversational tells The Context Company that this run involves direct user interaction.

This is important because conversational runs are the only runs monitored for user insights, such as user confusion, frustration, or any other custom insights you want to track. Runs that are not marked as conversational (e.g. background jobs, cron tasks, or internal automations) are excluded from user insight analysis.

<Tabs>
  <Tab title="TypeScript">
    Mark a run as conversational by setting `conversational` to `true` in the `tcc` parameter:

    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query } = instrumentClaudeAgent(claudeSDK);

    const result = query({
      // ...
      tcc: {
        conversational: true,
      },
    });
    ```
  </Tab>

  <Tab title="Python">
    Mark a run as conversational by setting `conversational=True` on `TCCConfig`:

    ```python agent.py theme={null}
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(conversational=True),
    ):
        ...
    ```
  </Tab>
</Tabs>

<Note>
  `conversational`, `sessionId`, and `runId` are typed shortcuts for the reserved [TCC metadata keys](/concepts#tcc-metadata-keys). Setting them via `metadata` directly (e.g. `"tcc.conversational": true`) works the same.
</Note>

## Identifying the agent

If your product ships more than one named agent, set the reserved `tcc.agent` metadata key to scope the run to a specific [agent](/concepts#agents). The dashboard's top-level agent selector, per-agent patterns and recaps, and the `agent` filter on the [REST API](/access-data/api) and [MCP tools](/access-data/mcp) all read from this key.

<Tabs>
  <Tab title="TypeScript">
    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query } = instrumentClaudeAgent(claudeSDK);

    const result = query({
      // ...
      tcc: {
        metadata: {
          "tcc.agent": "support-agent",
        },
      },
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python agent.py theme={null}
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(metadata={
            "tcc.agent": "support-agent",
        }),
    ):
        ...
    ```
  </Tab>
</Tabs>

<Note>
  Agent names that collide with reserved dashboard routes (for example `runs`, `sessions`, `patterns`, `recaps`, `overview`, `search`, `failures`, `feedback`, `tools`, `topics`, `views`, `settings`, `mcp-and-api`) are dropped.
</Note>

## Identifying users and organizations

Attach the end user and their organization to a run as first-class identity using the reserved `tcc.userId`, `tcc.userName`, `tcc.orgId`, and `tcc.orgName` metadata keys. This is **not the same** as adding a `userId` field to custom metadata — these keys promote user and org identity to dedicated dashboard filters and unlock native user/org search, per-user views, and per-org analytics. See [User and organization identity](/concepts#user-and-organization-identity) for the full concept.

Set these whenever you have a stable identifier for the end user or their organization in your product.

<Tabs>
  <Tab title="TypeScript">
    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query } = instrumentClaudeAgent(claudeSDK);

    const result = query({
      // ...
      tcc: {
        metadata: {
          "tcc.userId": "user-123",
          "tcc.userName": "Jane Doe",
          "tcc.orgId": "org-456",
          "tcc.orgName": "Acme Inc.",
        },
      },
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python agent.py theme={null}
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(metadata={
            "tcc.userId": "user-123",
            "tcc.userName": "Jane Doe",
            "tcc.orgId": "org-456",
            "tcc.orgName": "Acme Inc.",
        }),
    ):
        ...
    ```
  </Tab>
</Tabs>

<Note>
  `tcc.userName` and `tcc.orgName` require the corresponding ID (`tcc.userId` / `tcc.orgId`) to also be set. Names without IDs are dropped.
</Note>

## Debug mode

You can enable debug mode, which will log any spans that are created and exported.

<Tabs>
  <Tab title="TypeScript">
    ```typescript agent.ts theme={null}
    import { instrumentClaudeAgent } from "@contextcompany/claude";
    import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";

    const { query } = instrumentClaudeAgent(claudeSDK);

    const result = query({
      // ...
      tcc: {
        debug: true, // Enable debug mode
      },
    });
    ```
  </Tab>

  <Tab title="Python">
    Enable debug logging for a single call by setting `debug=True` on `TCCConfig`. You can also set the `TCC_DEBUG=true` environment variable to enable it globally.

    ```python agent.py theme={null}
    from contextcompany.claude import instrument_claude_agent, TCCConfig

    agent = instrument_claude_agent()

    async for message in agent.query(
        prompt="Hello!",
        tcc_config=TCCConfig(debug=True),  # Enable debug mode
    ):
        ...
    ```
  </Tab>
</Tabs>
