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

# Mesh connector

# MeshConnector

```typescript theme={null}
import { MeshConnector, DEFAULT_SVANTIC_URL } from '@svantic/sdk/mesh';
```

## What it is

`MeshConnector` owns the Svantic platform connection on behalf of an [`Agent`](./agent). It is responsible for:

* **Authentication** — exchanging your `client_id` / `client_secret` for a JWT (or accepting a pre-issued token).
* **Registration** — telling Svantic the agent exists, what capabilities it has, and how to reach it.
* **Transport** — in connected mode, dialing an outbound WebSocket; in hosted mode, leaving dispatches to hit the agent's public URL.
* **Liveness** — sending heartbeats so the gateway keeps the agent marked healthy.
* **Session lifecycle** — creating and closing Svantic sessions from the agent side.

`new Agent({ mesh: { … } })` + `await agent.start()` constructs a `MeshConnector` under the hood, so in most cases you don't import this class at all.

## When to use it

Import `MeshConnector` directly when you want the agent endpoints on an Express app you already own:

* You're using [`agent.expose(app)`](./agent#exposeapp-endpoint_path) instead of `agent.start()`.
* You're running multiple agents in one process and want fine-grained lifecycle control.
* You're managing the token yourself (e.g. a BFF forwarding a user JWT).

For the one-call Express embedding pattern, use [`attach`](./attach) — it wires `MeshConnector` for you.

## Functional usage

```typescript theme={null}
import express from 'express';
import { Agent } from '@svantic/sdk';
import { MeshConnector } from '@svantic/sdk/mesh';

const app = express();
app.use(express.json());

// 1. Build the agent and register its capabilities.
const agent = new Agent({
  name: 'orders-agent',
  description: 'Order management agent.',
  public_url: 'https://api.acme.com',
});
agent.define_capability({ /* … */ });

// 2. Mount A2A endpoints (/send + /.well-known/agent-card.json) on your app.
agent.expose(app);

// 3. Build the connector with credentials.
const mesh = new MeshConnector(agent, {
  client_id: process.env.SVANTIC_CLIENT_ID!,
  client_secret: process.env.SVANTIC_CLIENT_SECRET!,
});

// 4. connect() does: auth → register → open transport → start heartbeat.
await mesh.connect();

app.listen(4000);

// 5. On shutdown, disconnect() stops the heartbeat, closes the
//    WebSocket, and tells Svantic to deregister.
process.on('SIGTERM', () => mesh.disconnect());
```

Two advanced patterns the connector enables:

* **Token rotation** — when you're forwarding a user JWT (e.g. a dashboard session token) that the caller rotates periodically, call `mesh.refresh_token(new_jwt)` whenever the token changes. No reconnect needed.
* **Runtime capability changes** — after `agent.define_capability(...)` at runtime, call `mesh.re_register()` so the gateway sees the updated tool list without a full reconnect.

## Constants

### `DEFAULT_SVANTIC_URL`

```typescript theme={null}
export const DEFAULT_SVANTIC_URL = 'https://api.svantic.com';
```

Used whenever `svantic_url` is omitted from a `MeshConnectorConfig`.

## Constructor

```typescript theme={null}
new MeshConnector(agent: Agent, config: MeshConnectorConfig)
```

See [`MeshConnectorConfig`](./types#meshconnectorconfig) for every option. The most common shapes:

```typescript theme={null}
// Credential mode — SDK exchanges client_id/secret for a JWT.
new MeshConnector(agent, {
  client_id: process.env.SVANTIC_CLIENT_ID!,
  client_secret: process.env.SVANTIC_CLIENT_SECRET!,
});

// Token mode — caller supplies a pre-issued JWT (e.g. forwarded from a dashboard session).
new MeshConnector(agent, { token: bearer_token });
```

At least one of `(client_id + client_secret)` or `token` must be set.

## Lifecycle

### `connect()`

```typescript theme={null}
await mesh.connect();
```

1. If no `token` was supplied, exchange credentials for a JWT.
2. Register the agent with Svantic (capabilities, `deployment_mode`, optional `dispatch_auth`, learning config).
3. In connected mode, open the outbound WebSocket; in hosted mode this step is a no-op.
4. Start the heartbeat.

Throws if authentication, registration, or the WebSocket handshake fails. Throws are wrapped with clear error context so the caller's `try/catch` sees a descriptive message.

### `disconnect()`

```typescript theme={null}
await mesh.disconnect();
```

Best-effort teardown: stops the heartbeat, closes the WebSocket, sends `POST /agents/deregister`, and clears the cached token. Safe to call when not connected.

### `re_register()`

```typescript theme={null}
await mesh.re_register();
```

Re-register with Svantic without disconnecting. Use this after adding capabilities at runtime so the gateway sees the refreshed tool list. Throws if the connector is not currently connected.

### `refresh_token(jwt)`

```typescript theme={null}
mesh.refresh_token(new_jwt);
```

Replace the JWT used for all subsequent gateway calls. Useful in token-mode deployments (e.g. a BFF forwarding a rotated dashboard session token).

## Sessions

### `create_session(options?)`

```typescript theme={null}
const session_id = await mesh.create_session();
const scoped = await mesh.create_session({ user_id: 'user_42' });
```

Create a platform session bound to this agent instance. Returns the server-generated `session_id`. Throws when not connected.

### `close_session(session_id)`

```typescript theme={null}
await mesh.close_session(session_id);
```

Mark a session as completed. Throws when not connected.

## Properties

| Property          | Type                              | Description                                                              |
| ----------------- | --------------------------------- | ------------------------------------------------------------------------ |
| `connected`       | `boolean`                         | `true` while a registration is active.                                   |
| `svantic_url`     | `string`                          | The resolved Svantic URL (respects `DEFAULT_SVANTIC_URL`).               |
| `token`           | `string \| null`                  | Current JWT, or `null` before `connect()` / after `disconnect()`.        |
| `deployment_mode` | `'connected' \| 'hosted' \| null` | Resolved mode from the registration response. `null` before `connect()`. |
| `agent`           | `Agent`                           | The wrapped agent.                                                       |
| `ws_transport`    | `WsTransport \| null`             | The underlying WebSocket transport in connected mode; otherwise `null`.  |

## See also

* [Connecting to Svantic](../guides/connecting) — when to pick connected vs. hosted.
* [`MeshConnectorConfig`](./types#meshconnectorconfig)
* [Attach to Express](../guides/attach-to-express)
