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

# Connect your agent

> Install mirrors-sdk and add context retrieval at your existing user-turn boundary.

This guide uses **Node.js 22 or later** and `mirrors-sdk@0.6.2`. The package supports
ES modules and CommonJS and has no runtime or peer dependencies.

## 1. Get connection settings

Open your agent in the [Mirrors dashboard](https://platform.runmirrors.com), then
open **Agent setup → SDK connection settings**. Copy the API URL and agent ID.
The agent ID is a generated identifier, not the agent's display name.

Use an agent SDK key with `runtime:read` and `runtime:write` permissions. Store
these settings on your server:

```sh theme={null}
MIRRORS_API_URL=your-api-url
MIRRORS_AGENT_ID=your-agent-id
MIRRORS_API_KEY=your-sdk-key
```

Keep the key out of browser bundles, source control, and application logs. If your
account has no product access, contact the Mirrors team to enable your workspace.

## 2. Install and initialize

```sh theme={null}
npm install mirrors-sdk@0.6.2
```

Create one long-lived client for this agent, rather than one client per message.

```ts theme={null}
import { Mirrors, type CanonicalTrace } from "mirrors-sdk";

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

const mirrors = new Mirrors({
  apiUrl: requiredEnv("MIRRORS_API_URL"),
  agentId: requiredEnv("MIRRORS_AGENT_ID"),
  apiKey: requiredEnv("MIRRORS_API_KEY"),
});
```

## 3. Capture originals and retrieve context

At your existing user-turn boundary, create a faithful snapshot of the conversation
so far. Use one unique trace ID for the whole execution, preserving it across turns.
See [trace capture](/docs/guides/trace-capture) for the message format.

The helper below returns the system prompt for your existing model call. It does not
call the model or change your tool, stream, or error handling.

```ts theme={null}
async function systemPromptForTurn(
  originalSystemPrompt: string,
  originalTrace: CanonicalTrace,
  signal: AbortSignal,
): Promise<string> {
  mirrors.captureTrace({ trace: originalTrace, final: false });

  const result = await mirrors.getContext(
    { trace: originalTrace },
    { signal, timeoutMs: 1000 },
  );
  signal.throwIfAborted();

  return result.context
    ? `${originalSystemPrompt}\n\n${result.context}`
    : originalSystemPrompt;
}
```

Use the returned prompt immediately in the same turn. Keep original history
separate from the augmented prompt so the SDK's context is never captured as
original conversation evidence. If history changes before the model call, retrieve
fresh context. If dispatch is delayed, check `result.freshness.expiresAt` before
using a result, or retrieve again.

Context retrieval has a total wait budget of up to 1,000 ms, including copying,
worker scheduling, and transport. A blocked JavaScript event loop can delay timers.
You can shorten the budget with `timeoutMs`. Do not repeat retrieval at every
internal tool step unless you intentionally want that additional wait.

## 4. Finish the conversation

After recording the last response and tool results, submit the full final snapshot.
Call this at actual conversation completion, not when a stream first opens or a
single tool returns.

```ts theme={null}
async function recordCompletion(completedOriginalTrace: CanonicalTrace) {
  const ticket = mirrors.captureTrace({
    trace: completedOriginalTrace,
    final: true,
    terminal: "completed",
  });
  return ticket.done; // Observe outside the model's execution path.
}

async function shutdown() {
  const result = await mirrors.flush({ timeoutMs: 2000 });
  mirrors.dispose();
  return result;
}
```

Use `terminal: "failed"` or `"canceled"` when appropriate. These describe how the
execution ended, not whether the agent solved the user's task. If you have no final
evidence, call `releaseTrace(traceId)` for local cleanup. Never reuse a finished ID.

## 5. Verify before activating

Start in [shadow mode](/docs/guides/runtime-modes). Check capture receipts and confirm
completed conversations appear in Mirrors. `accepted` with ingestion `queued`
means analysis was queued, not finished.

Empty context is expected in shadow mode and while the SDK first learns the agent's
mode. Review a correction, preview its scope, then deliberately enable active
delivery when ready. See [troubleshooting](/docs/guides/troubleshooting) if capture or
retrieval does not behave as expected.


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