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

# Getting Started

> Install the Klef CLI, scaffold a connector, write it, and test it against your own tenant.

This guide builds `custom_acme`, a target connector for an app called Acme that speaks SCIM 2.0. By the end, it reads Acme's users, creates and updates them, and passes Klef's conformance tests and journey against your Acme test tenant.

## Before You Begin

You need the [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0).

## Install the Klef CLI

The CLI is a .NET tool on NuGet:

```bash theme={null}
dotnet tool install --global Klef.Cli
klef --version
```

Update it later with `dotnet tool update --global Klef.Cli`.

## Scaffold a Connector

```bash theme={null}
klef connectors new custom_acme
```

The id is snake\_case and starts with `custom_`, which marks a connector your workspace owns. Klef never ships an id with that prefix. A connector declares an account object by default, which Klef writes into; pass `--object worker` for an HR system Klef reads workers from. What Klef uses a connector for follows from the objects its manifest declares. A source keeps the rules in [What a Source Returns](https://klef.ai/docs/connector-sdk.md#what-a-source-returns).

The command makes:

```
custom_acme/
├── connector.yaml                  # the manifest
├── Klef.Connectors.Acme.csproj
├── AcmeConnector.cs                # your code
├── AcmeUserMapper.cs
├── docs/setup.mdx                  # how an admin makes the credentials
├── assets/logo.svg
├── tests/
│   ├── Klef.Connectors.Acme.Tests.csproj
│   ├── AcmeConformance.cs          # conformance, from the kit
│   ├── AcmeLive.cs                 # the journey, from the kit
│   └── AcmeLiveTenant.cs           # your test tenant
└── .gitignore
```

Names come from the id without its prefix, so `custom_acme` makes `AcmeConnector`. Building the project generates more from the manifest:

| Generated | Holds |
| - | - |
| `AcmeConnector.Manifest` | The parsed manifest. |
| `AcmeFields` | A constant per account field, such as `AcmeFields.UserName`. |
| `AcmeConfig` | The connection's values, such as `BaseUrl`, read with `context.Config<AcmeConfig>()`. |

## Write the Manifest

`connector.yaml` tells Klef what the connector is before any code runs. Replace the scaffold's with this one:

```yaml connector.yaml theme={null}
format: klef.connector/v1
id: custom_acme
name: Acme
version: "1.0"

presentation:
  docs: docs/setup.mdx

connection:
  fields:
    - key: baseUrl
      label: SCIM base URL
      kind: text
      required: true
      description: The app's SCIM 2.0 root.
    - key: token
      label: Bearer token
      kind: password
      required: true
      secret: true
      description: The app's SCIM token.

auth:
  kind: bearer
  token_field: token

egress:
  - "{{ connection.baseUrl | host }}"

objects:
  - kind: account
    key: user
    label: User
    default_match_rules:
      - { target_field: userName, worker_field: business_email }
    provisioning:
      operations: [create, disable]
    fields:
      - key: userName
        type: string
        label: User name
        required: true
        description: The name the user signs in with.
      - key: displayName
        type: string
        label: Display name
        description: The name the app shows.
      - key: active
        type: bool
        disabled_when: false
        label: Active
        description: Whether the user can sign in.
```

What each part does:

| Key | Purpose |
| - | - |
| `connection` | The values a connection needs. `secret: true` marks what is redacted everywhere. |
| `auth` | How requests sign in. Here, the `token` field as a bearer token. |
| `egress` | The only hosts the connector may call. A request anywhere else is refused. Here, the host of the `baseUrl` field. |
| `objects` | The kinds of thing the app has. Here, one account and its fields. `default_match_rules` suggest which existing account is a worker's, by comparing a worker field with an account field. A person confirms each match when adopting accounts. Klef never adopts one on its own. |
| `provisioning` | What Klef can do to an account. `operations` lists `create`, `invite`, `disable` and `delete`, and decides which values a policy may give `status`. |
| `disabled_when` | Marks the field that shows the status, and the value that means disabled. Policies set `status`, and the SDK writes and reads this field for you. |

An account that holds a password or a pass lists it under `credentials`, beside `fields`. Each credential has a `key`, a `label`, the `operations` it supports, and its own `fields`. A secret is a field with `secret: true`: `mutability: write_only` when Klef supplies it, such as a password Klef makes to the field's `min_length` and `max_length`, or `read_only` when the vendor returns it, such as a pass. Klef never stores either in plain text.

```yaml theme={null}
    credentials:
      - key: password
        label: Password
        operations: [create]
        fields:
          - { key: password, type: string, label: Password, mutability: write_only, secret: true, min_length: 8, max_length: 256 }
          - { key: forceChange, type: bool, label: Change at next sign-in }
```

A policy issues a credential with a block named for it inside a target, and revokes it with `status = removed` where its operations include `delete`. Klef sends it in `DesiredPrincipal.Credentials` on a create or an update, and the connector answers what it issued, with any returned secret, in `WriteOutcome.Done.Credentials`. A connector whose accounts hold credentials also implements `ISupportsSignInUrl`, and returns the tenant's password rules, when it has any, in its connection check's `PasswordRules`.

Check it as you go. This needs no tenant:

```bash theme={null}
klef connectors validate
```

It reports what the schema refuses and what does not add up across keys, such as a `disabled_when` field on an account that cannot `disable`.

## Write the Connector

A target implements `ITargetConnector` to read, and `ISupportsPrincipalWrites` to create and update accounts. The SDK's `ScimClient` speaks SCIM, so the connector only maps Acme's users to the manifest's fields. A list call reads one page of the vendor's own, at most the size Klef asks for, and returns the vendor's next cursor, or the end after its last page. Klef keeps the cursor and asks again until the list ends:

```csharp AcmeConnector.cs theme={null}
using System.Text.Json.Nodes;
using Klef.Connectors.Model;
using Klef.Connectors.Sdk;
using Klef.Connectors.Sdk.Payloads;
using Klef.Connectors.Sdk.Scim;

namespace Klef.Connectors.Acme;

public sealed partial class AcmeConnector : ITargetConnector, ISupportsPrincipalWrites
{
    private static readonly string[] Attributes =
    [
        AcmeFields.UserName,
        AcmeFields.DisplayName,
        AcmeFields.Active,
    ];

    public JsonObject Normalize(JsonObject payload)
    {
        var canonical = (JsonObject)payload.DeepClone();
        if (TargetPayload.Str(canonical, AcmeScimFields.UserName) is { } userName)
        {
            canonical[AcmeScimFields.UserName] = userName.Trim().ToLowerInvariant();
        }

        return canonical;
    }

    public async Task<ConnectionCheck> CheckConnectionAsync(
        ConnectionContext context,
        CancellationToken cancellationToken
    )
    {
        await Client(context).PageAsync(ScimClient.Users, 1, 1, cancellationToken);

        return ConnectionCheck.Passed;
    }

    public async Task<Page<Principal>> ListPrincipalsAsync(
        ConnectionContext context,
        string kind,
        PageRequest page,
        CancellationToken cancellationToken
    )
    {
        var users = await Client(context).PageAsync(ScimClient.Users, page, cancellationToken);

        return new Page<Principal>([.. users.Items.Select(User)], users.Next);
    }

    public async Task<PrincipalRead> GetPrincipalAsync(
        ConnectionContext context,
        string kind,
        string id,
        JsonObject? desired,
        CancellationToken cancellationToken
    )
    {
        var user = await Client(context).GetAsync(ScimClient.Users, id, cancellationToken);

        return user is null ? new PrincipalRead.Absent() : new PrincipalRead.Held(User(user));
    }

    public async Task<Principal> CreatePrincipalAsync(
        ConnectionContext context,
        DesiredPrincipal desired,
        CancellationToken cancellationToken
    )
    {
        var scim = Client(context);
        var payload = Normalize(desired.Payload);
        var userName =
            TargetPayload.Str(payload, AcmeFields.UserName)
            ?? throw new ConnectorException(
                new ConnectorFailure(FailureKind.Refused, "A user needs a user name.")
            );

        if (
            await scim.FindAsync(
                ScimClient.Users,
                ScimClient.Equal("userName", userName),
                cancellationToken
            ) is
            { } existing
        )
        {
            return User(existing) with { Adopted = true };
        }

        var body = new JsonObject
        {
            ["schemas"] = new JsonArray(JsonValue.Create(ScimClient.UserSchema)),
        };
        foreach (var key in Attributes.Where(key => payload[key] is not null))
        {
            body[key] = payload[key]!.DeepClone();
        }

        return User(await scim.CreateAsync(ScimClient.Users, body, cancellationToken));
    }

    public async Task<Principal> UpdatePrincipalAsync(
        ConnectionContext context,
        string id,
        DesiredPrincipal desired,
        CancellationToken cancellationToken
    )
    {
        var scim = Client(context);
        var current = await scim.GetUserAsync(id, cancellationToken);
        var held = User(current).Fields;
        var payload = Normalize(desired.Payload);
        List<ScimOperation> changes =
        [
            .. Attributes
                .Where(key =>
                    payload.ContainsKey(key) && !JsonNode.DeepEquals(payload[key], held[key])
                )
                .Select(key => ScimOperation.Replace(key, payload[key]?.DeepClone())),
        ];
        if (changes.Count is 0)
        {
            return User(current);
        }

        await scim.PatchUserAsync(id, changes, cancellationToken);

        return User(await scim.GetUserAsync(id, cancellationToken));
    }

    private static ScimClient Client(ConnectionContext context) =>
        new(
            context.Http,
            new Uri(
                context.Config<AcmeConfig>().BaseUrl
                    ?? throw new InvalidOperationException("The connection has no base URL.")
            )
        );

    private Principal User(JsonObject user)
    {
        var fields = new JsonObject();
        foreach (var key in Attributes.Where(key => user[key] is not null))
        {
            fields[key] = user[key]!.DeepClone();
        }

        var canonical = Normalize(fields);

        return new Principal
        {
            Kind = AcmeObjects.User,
            Id = ScimClient.Id(user),
            Label = PrincipalLabel.From(
                TargetPayload.Str(canonical, AcmeFields.DisplayName),
                TargetPayload.Str(canonical, AcmeFields.UserName)
            ),
            Fields = canonical,
            MatchKey = TargetPayload.Str(canonical, AcmeFields.UserName),
        };
    }
}
```

A few things the SDK does for you:

* **`context.Http` applies the manifest.** It signs each request, refuses hosts outside `egress`, and applies limits and retries. Send every request through it.
* **Failures are typed.** A refused call throws `ConnectorException` with a `FailureKind`, such as `AuthRejected` or `ObjectGone`, which Klef shows and acts on the same way as for its own connectors. A gone or existing object is named, as in `ConnectorException.ObjectGone(AcmeObjects.User, id)`. Klef counts a removal done only when the gone object is the account it removes.
* **The connection check names problems.** `CheckConnectionAsync` returns a `ConnectionProblem` for each thing that stops Klef using the connection, such as a missing permission, worded as one of the manifest's `messages`. A problem that does not block is a warning. Acme's check passes once the list call works.
* **Writes are idempotent.** `CreatePrincipalAsync` returns an account that already exists with `Adopted` set, rather than making a second, so a retried plan never duplicates anyone. Klef does not take that account on by itself: the plan reports it for a person to [adopt](https://klef.ai/docs/adoption.md).

Delete `AcmeUserMapper.cs` if, as here, the connector maps in one place. Every type is in the [Reference](https://klef.ai/docs/connector-sdk/reference.md).

## Test It

The kit tests a connector against a real tenant, not a mock: conformance checks each method on its own, and the journey runs a worker through hire, changes and leaving.

**1. Describe your test tenant**

`AcmeLiveTenant` tells the kit about your tenant: an existing member to read, how to name and make a new account, and how to inspect and remove one.

```csharp tests/AcmeLiveTenant.cs theme={null}
using System.Text.Json.Nodes;
using Klef.Connectors.Sdk;
using Klef.Connectors.Sdk.Scim;
using Klef.Connectors.Testing;

namespace Klef.Connectors.Acme.Tests;

public sealed class AcmeLiveTenant : LiveTenant, IDisposable
{
    private readonly LiveConnection _connection = new(AcmeConnector.Manifest);

    public override ConnectionContext Context => _connection.Context;

    public override ConnectionContext RefusedContext => _connection.RefusedContext;

    public override IReadOnlyList<string> Members =>
        [_connection.Require("memberUserName").Trim().ToLowerInvariant()];

    public override IReadOnlyDictionary<string, IReadOnlyList<string>> Entitlements =>
        new Dictionary<string, IReadOnlyList<string>>();

    public override string MissingId => $"{Prefix}missing";

    public override string IdentityField => AcmeFields.UserName;

    public override string NewIdentity(string name) =>
        $"{name}@{_connection.Require("emailDomain")}".ToLowerInvariant();

    public override JsonObject NewAccount(string name) =>
        new()
        {
            [AcmeFields.UserName] = NewIdentity(name),
            [AcmeFields.DisplayName] = name,
            [AcmeFields.Active] = true,
        };

    public override async Task DeleteAccountAsync(
        string externalId,
        CancellationToken cancellationToken
    ) => await Client().DeleteAsync(ScimClient.Users, externalId, cancellationToken);

    public override async Task<TenantAccount?> InspectAsync(
        string externalId,
        CancellationToken cancellationToken
    ) =>
        await Client().GetAsync(ScimClient.Users, externalId, cancellationToken) is { } user
            ? new TenantAccount(
                user["active"]?.GetValue<bool>() is false ? TenantStanding.Off : TenantStanding.On,
                new Dictionary<string, IReadOnlyCollection<string>>()
            )
            : null;

    public void Dispose() => _connection.Dispose();

    private ScimClient Client() =>
        new(Context.Http, new Uri(Context.Config<AcmeConfig>().BaseUrl!));
}
```

**2. Sign in to the tenant**

```bash theme={null}
klef connectors login
```

It asks for each value the manifest declares, here `baseUrl`, `token`, `memberUserName` and `emailDomain`, and saves them in `connection.local.yaml`, which the scaffold's `.gitignore` keeps out of git. In CI, set them as environment variables instead, such as `E2E__Acme__token`.

**3. Run the tests**

```bash theme={null}
klef connectors test
```

It runs conformance, then the journey, and removes every account they made. Run one part with `klef connectors test conformance` or `klef connectors test journey`, and list every test with `klef connectors test --list`.

> [!TIP]
>
> The tests use a budget of accounts per run, and every account they make carries a prefix, so a run that stops halfway is swept up by the next one.

## Run It in Klef

Once the tests pass:

**1. Push a draft**

Create an [API key](https://klef.ai/docs/how-to/manage-api-keys.md) with the **Manage connections** permission, then:

```bash theme={null}
KLEF_API_KEY=<your key> klef connectors push --workspace acme
```

`acme` is your workspace's subdomain. The revision appears as a draft under **Connections > Custom connectors**.

**2. Serve the connector**

On a machine on your network with the .NET SDK, in the connector's directory:

```bash theme={null}
klef connectors serve
```

It builds the connector and serves its calls over HTTP on `127.0.0.1:7001`. Set `CONNECTOR_LISTEN` to serve on another loopback port, or on a unix socket such as `unix:/run/acme.sock`. The connector reads its connection values the same way the tests do, from `E2E__Acme__*` environment variables or `connection.local.yaml`, so give it your production values there. It knows nothing of Klef and holds no Klef key.

**3. Start the relay**

Under **Connections > Custom connectors**, select **New key** under the connector's **Runner keys**, and copy the key it shows. On the same machine:

```bash theme={null}
KLEF_RUNNER_KEY=<runner key> klef relay --workspace acme
```

The relay reads the manifest from the connector, registers it with Klef, and forwards each of Klef's calls to the connector. Pass `--connector` when the connector does not listen on `127.0.0.1:7001`. The relay calls out to Klef over HTTPS; nothing calls in. It reaches the connector over plain HTTP, which is why the connector listens only on loopback or a unix socket: run the two on one machine, or in one pod.

**4. Activate**

An Owner opens the revision and selects **Activate**. Plans use the connector from then on.

To change the connector later, push a new revision, start the new build on another port with its own relay, have an Owner activate it, then stop the old connector and its relay.


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