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

# How It Works

> The secret sauce behind AgentCat.

Here's what's going on under the hood — how the SDK captures data, how sessions work, and the key concepts you'll see throughout the docs.

## Architecture

AgentCat's SDK runs inside your MCP server, intercepting MCP protocol messages to capture analytics before passing them through to your tools. Your server works exactly as before. AgentCat just observes.

<Frame>
  <img src="https://mintcdn.com/mcpcat/p1h-WAAQvjrpHpEc/images/architecture.svg?fit=max&auto=format&n=p1h-WAAQvjrpHpEc&q=85&s=b53f476a436224f5d993e38e2723b3ee" alt="architecture" width="1122" height="542" data-path="images/architecture.svg" />
</Frame>

## Agent Intent Capture

The magic of AgentCat lies in understanding *why* agents call your tools, not just *what* they call.

When you install the SDK, AgentCat automatically injects a `context` parameter into your tool schemas. When AI assistants (like Claude Code or Cursor) call your tools, they see this additional parameter, they use it to explain their reasoning for making that tool call.

```json theme={null}
{
  "tool": "search_files",
  "arguments": {
    "query": "authentication",
    "context": "Looking for authentication logic to understand how user sessions are validated before adding a new permission check"
  }
}
```

You can [customize or disable](/sdk/tool-call-context) this behavior.

This context is extracted as the agent's intent, giving you insights into:

* What users are trying to accomplish
* How tools fit into larger workflows
* Common patterns and use cases
* Missing functionality users need

## Request Tracing

AgentCat intercepts all MCP protocol messages by wrapping your server's handlers:

<CodeGroup>
  ```python Python theme={null}
  import agentcat
  from mcp.server import FastMCP

  # Your existing server

  server = FastMCP(name="my-tools")

  # One line to add analytics

  agentcat.track(server, "proj_YOUR_PROJECT_ID")

  ```

  ```typescript TypeScript theme={null}
  import { track } from 'agentcat';
  import { Server } from '@modelcontextprotocol/sdk';

  // Your existing server
  const server = new Server();

  // One line to add analytics
  track(server, "proj_YOUR_PROJECT_ID");
  ```

  ```go Go theme={null}
  import mcpcat "github.com/mcpcat/mcpcat-go-sdk/officialsdk"
  // For mark3labs/mcp-go: import mcpcat "github.com/mcpcat/mcpcat-go-sdk/mcpgo"

  // Your existing server
  s := mcp.NewServer(&mcp.Implementation{Name: "my-tools", Version: "1.0.0"}, nil)

  // One line to add analytics
  mcpcat.Track(s, "proj_YOUR_PROJECT_ID", nil)
  ```
</CodeGroup>

Every request is captured with:

* **Event type** (tool call, resource access, prompt execution)
* **Timing data** (start time, duration)
* **Request parameters** and **response data**
* **Error states** and messages
* **Client information** (which AI tool made the request)

## How it Works Under the Hood

### 1. Schema Enhancement

When AgentCat wraps your server, it modifies tool schemas to include the context parameter:

**Before AgentCat:**

```json theme={null}
{
  "name": "search_files",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": { "type": "string" }
    }
  }
}
```

**After AgentCat:**

```json theme={null}
{
  "name": "search_files",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": { "type": "string" },
      "context": {
        "type": "string",
        "description": "Describe why you are calling this tool..."
      }
    },
    "required": ["query", "context"]
  }
}
```

### 2. Transparent Interception

AgentCat intercepts requests without affecting your tool's functionality:

1. **Client calls tool** with arguments + context
2. **AgentCat extracts** the context parameter
3. **Your tool receives** original arguments (without context)
4. **Tool executes** normally
5. **AgentCat captures** the response
6. **Event is queued** for analytics

Your tools never see the context parameter—they work exactly as before.

### 3. Asynchronous Processing

Events are processed asynchronously to ensure zero performance impact:

* Thread-safe queue holds events (default: 10,000 capacity)
* Worker threads send events to AgentCat API
* Automatic retries with exponential backoff
* Graceful shutdown ensures no data loss

### 4. Privacy & Control

AgentCat is designed with [privacy](/privacy-security) in mind:

* **[Redaction functions](/privacy-security/client-side-redaction)** let you scrub sensitive data before sending
* **All data [encrypted](/privacy-security/certifications)** at rest
* **You control** what events are tracked
* **No PII required** - user identification is optional

## Sessions

Every interaction with your MCP server happens within a **session**. How sessions are created depends on your server's settings:

* **Stateful servers**: The SDK generates a session ID when a client connects. All events during that connection share the same session.
* **Stateless servers**: Each request is independent, so the SDK sends events without a session ID. AgentCat's backend groups these events into sessions automatically based on the identified user, the client used, and a 30-minute inactivity window. See [Stateless Servers](/sdk/stateless-servers) for setup details.

<Frame>
  <img src="https://mintcdn.com/mcpcat/rAg26YlX8tmGTobY/images/session-lifecycle.svg?fit=max&auto=format&n=rAg26YlX8tmGTobY&q=85&s=e4b3860f86e5c36c06e1f8ed31100af1" alt="session lifecycle" width="1100" height="140" data-path="images/session-lifecycle.svg" />
</Frame>

Sessions follow a simple lifecycle:

1. **Initialization**: A new session starts when a client initializes a connection to your MCP server
2. **Activity**: All tool invocations and interactions are associated with the session
3. **Inactivity**: Sessions remain active as long as the client maintains the connection
4. **Termination**: Sessions end when the client disconnects or after a period of inactivity (usually 30 minutes)

<Note>
  For stateless HTTP servers, sessions don't have an explicit initialization or termination. Instead, AgentCat groups events into sessions server-side based on user identity and timing. Learn more in [Stateless Servers](/sdk/stateless-servers).
</Note>

### Session Construction

Sessions are constructed in two phases — first by the SDK on the client, then refined by the server.

#### Client-Side (SDK)

The SDK intercepts your MCP server's transport layer and automatically captures every interaction without requiring any code changes to your tools. When a client connects, the SDK:

1. **Generates a unique session ID** (stateful) or **signals stateless mode** so the server can group events — and associates all subsequent events accordingly
2. **Captures metadata** about the connection, like client name and version, server name and version, and SDK language and version
3. **Records each interaction** as a structured event with tool calls, resource reads, prompt requests, along with timing data, parameters, and responses
4. **Streams events asynchronously** to AgentCat's ingestion pipeline so there is zero impact on your server's response times

The SDK is designed to be resilient. Events are buffered and sent independently of your tool execution, so even if the network is momentarily unavailable, your MCP server continues to operate normally.

#### Server-Side Processing

Once events arrive, AgentCat's server reconstructs and enriches each session through several processing stages:

1. **Session assembly**: Events are matched to their session using atomic, concurrent-safe operations. If a session doesn't exist yet, it's created on the first event. Metadata fields are progressively backfilled: if the first event is missing client info, later events in the same session can fill in the gaps. For stateless servers, events arrive without a session ID, and AgentCat groups them by matching the identified user and AI client within a 30-minute window. This requires [user identification](/sdk/identifying-users) — anonymous stateless events each get their own isolated session.

2. **Session consolidation**: Some MCP clients (like Claude Desktop) reset session identifiers mid-conversation. AgentCat detects these inconsistencies and automatically merges fragmented sessions back together, so you see one continuous interaction instead of several broken ones.

3. **Counter denormalization**: As events arrive, session-level metrics (total events, tool calls, errors, missing tool indicators) are updated atomically. This means your dashboard queries are fast even across thousands of sessions, without needing to re-aggregate raw events on every page load.

4. **Error grouping**: When an error occurs during a tool call, AgentCat parses the error, computes a fingerprint, and groups it with similar errors across sessions. This surfaces recurring issues automatically rather than burying them in individual session logs.

5. **Goal categorization**: After a session becomes inactive, AgentCat analyzes the sessions contents to classify an agent goal, giving you insight into *what users were trying to accomplish*, not just what tools they called. For more information, see [Agent Goals](/features/goals)

This multi-stage pipeline means sessions in AgentCat are more than simple event logs. They're structured, deduplicated, enriched records that give you a complete picture of every user interaction.

## Projects

Projects are the top-level organizational unit for your analytics. Each project represents a distinct MCP server or deployment, identified by a unique project ID (like `proj_abc123xyz`) that you use when initializing AgentCat tracking.

Organize your projects to match your needs:

* **By server type**: Separate projects for different MCP servers (database tools, file system tools, API integrations)
* **By environment**: Keep development, staging, and production data isolated
* **By customer or team**: Track usage across different customer deployments or internal teams

Each project maintains its own session history, usage metrics, error tracking, user identification, and [custom event tracking](/sdk/custom-events).

## What Gets Tracked

AgentCat tracks all MCP protocol events:

* **Tool Operations**: `tools/list`, `tools/call`
* **Resource Operations**: `resources/list`, `resources/read`
* **Prompt Operations**: `prompts/list`, `prompts/get`
* **Completions**: `completion/complete`
* **Server Lifecycle**: `initialize`, `initialized`
* **Custom Events**: [Your own analytics events](/sdk/custom-events)

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="bolt" href="/quickstart">
    Add analytics to your MCP server in minutes.
  </Card>

  <Card title="Dashboard" icon="layout-dashboard" href="/features/dashboard">
    Explore real-time KPIs and usage analytics.
  </Card>

  <Card title="Session Replay" icon="play" href="/features/session-replay">
    Step through individual sessions to debug issues.
  </Card>

  <Card title="Privacy & Security" icon="shield-check" href="/privacy-security">
    Learn how AgentCat protects your users' data.
  </Card>
</CardGroup>
