> ## 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.

This page explains how the SDK captures data, how sessions work, and the key concepts that you will 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.

![architecture](https://mintcdn.com/mcpcat/dPmgvnVHEbBWj6Zv/images/architecture.svg?fit=max\&auto=format\&n=dPmgvnVHEbBWj6Zv\&q=85\&s=e55c57357ca7b24b77e8f6e677f5e36b)

## 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](https://docs.agentcat.com/sdk/tool-call-context.md) 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:

```python Python theme={null}
import os

import agentcat
from mcp.server.fastmcp import FastMCP

server = FastMCP("my-server")
# @server.tool() ...
agentcat.track(server, os.environ["AGENTCAT_PROJECT_ID"])

server.run(transport="streamable-http")
```

```typescript TypeScript theme={null}
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import * as agentcat from "agentcat";

const handler = createMcpHandler(() => {
  const server = new McpServer({ name: "my-server", version: "1.0.0" });
  // server.registerTool(...)
  return agentcat.track(server, process.env.AGENTCAT_PROJECT_ID!);
});
```

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

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

// Add analytics
shutdown, err := agentcat.Track(s, os.Getenv("AGENTCAT_PROJECT_ID"), nil)
if err != nil {
    log.Fatal(err) // shutdown is nil when Track fails
}
defer shutdown(context.Background()) // sends queued events before exit
```

```php PHP theme={null}
use AgentCat\AgentCat;
use Mcp\Server;

// Your existing server
$builder = Server::builder()->setServerInfo('my-tools', '1.0.0');

// $builder->addTool(...) and your other capabilities

AgentCat::track($builder); // reads AGENTCAT_PROJECT_ID
```

```csharp C# theme={null}
// Your existing server
builder.Services.AddMcpServer()
    .WithHttpTransport(o => o.Stateless = true)
    .WithTools<MyTools>()
    .WithAgentCat();
```

```rust Rust theme={null}
// The handle reads AGENTCAT_PROJECT_ID.
let server = AgentCat::from_env(Options::default()).track(Calculator); // Calculator is your own ServerHandler

// Serve the tracked server where you served Calculator.
let running = server.serve(rmcp::transport::stdio()).await?;
```

In PHP, AgentCat runs in the request or process of your server, with no threads: it sends the events after the client has its answer wherever the runtime allows it, and [PHP runtimes](https://docs.agentcat.com/languages/php/reference.md#runtimes-delivery-and-shutdown) names the exceptions.

In C#, AgentCat adds request filters to the MCP server options and never replaces your handlers. It sends the events from a queue in the background, and when the host stops or the process ends, it sends the queued events in about 6 seconds at most (see [C# shutdown](https://docs.agentcat.com/languages/csharp/reference.md#shutdown)).

In Rust, AgentCat wraps your `rmcp` server handler in a `Tracked` server, which forwards every request to your handler. It records tool calls: tool listings, resources and prompts give no events. A tool call only puts its event in a queue, and a thread of the SDK sends it, so the call never waits for the network (see [Rust runtimes](https://docs.agentcat.com/languages/rust/reference.md#runtimes-delivery-and-shutdown)).

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](https://docs.agentcat.com/privacy-security.md) in mind:

* **[Redaction functions](https://docs.agentcat.com/privacy-security/client-side-redaction.md)** let you scrub sensitive data before sending
* **All data [encrypted](https://docs.agentcat.com/privacy-security/certifications.md)** at rest
* **You control** what events are tracked
* **No PII needed** - user identification is strongly recommended, and an anonymized ID is enough

## 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 transport has no session. AgentCat adds a `session_id` parameter to each tool instead: on its first call, the agent sends `start` and gets a `ses_` ID back, and it sends that ID on its later calls, so the calls of one task share a session. See [Stateless Servers](https://docs.agentcat.com/sdk/stateless-servers.md) for setup details.

![session lifecycle](https://mintcdn.com/mcpcat/dPmgvnVHEbBWj6Zv/images/session-lifecycle.svg?fit=max\&auto=format\&n=dPmgvnVHEbBWj6Zv\&q=85\&s=34743b35572e91e4568d32c9b6e87aea)

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 do not have an explicit initialization or termination. Instead, the `session_id` that the agent sends on each tool call ties the calls of one task to one session. Learn more in [Stateless Servers](https://docs.agentcat.com/sdk/stateless-servers.md).

### 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. **Issues a session ID for each task** through the injected `session_id` parameter, and associates the later events of that task with it
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 does not exist yet, it is 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, each event carries the `ses_` ID that the agent sent in the injected `session_id` parameter, so the events of one task meet in one session whichever server instance handled them.

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, agent feedback counts) 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](https://docs.agentcat.com/features/goals.md)

This multi-stage pipeline means sessions in AgentCat are more than simple event logs. They are 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](https://docs.agentcat.com/sdk/custom-events.md).

## 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](https://docs.agentcat.com/sdk/custom-events.md)

## Next Steps

> [card] [Quickstart](https://docs.agentcat.com/quickstart.md)
>
> Add analytics to your MCP server in minutes.

> [card] [Dashboard](https://docs.agentcat.com/features/dashboard.md)
>
> Explore real-time KPIs and usage analytics.

> [card] [Session Replay](https://docs.agentcat.com/features/session-replay.md)
>
> Step through individual sessions to debug issues.

> [card] [Privacy & Security](https://docs.agentcat.com/privacy-security.md)
>
> Learn how AgentCat protects your users' data.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.