---
url: https://kit.kambium.net/docs/kit-services.md
description: Server-side services supplied to Kambium Kit engine hooks and tasks.
---

# Kit services

Use the configured services on [EngineContext](https://kit.kambium.net/docs/kit-api.md#enginecontext) inside an engine hook or task. They already have the selected instance and its connection configuration.

| Context member | Reference | Use |
| --- | --- | --- |
| `airtable` | [AirtableService](#airtableservice) | Use `fetchRecord` for one ID, `listRecords` for a provider page, and `queryRecords` for a bounded result across pages. |
| `slack` | [SlackService](#slackservice) | Send or update messages, read threads, and check channel access. Keep the returned channel and timestamp when a later operation needs the same message. |
| `schema` | [SchemaCacheService](#schemacacheservice) | Read full-base or single-table schema. Use `getCachedSchemaIndex` when a cache miss must avoid a provider request. |
| `power` | [PowerService](#powerservice) | Share the scoped engine record and lazy provider clients across the operation. |
| `credentials` | [CredentialService](#credentialservice) | Store encrypted credentials and read the latest value for the engine, user, platform, and key type. |
| `initLlmService()` | [LlmService](#llmservice) | Reuse one service per operation. Use [RunStructuredPromptInput](#runstructuredpromptinput) for schema and model settings and [RunStructuredPromptResult](#runstructuredpromptresult) for the parsed data and usage. |
| `getExternalPostgres()` | [ExternalPostgresConnectionService](#externalpostgresconnectionservice) | Run queries against the engine's database. See [ExternalPostgresExecutorOptions](#externalpostgresexecutoroptions) before opting a callback into replay. |
| `ServerContext.initAuthService(request)` | [AuthService](#authservice) | Bind identity checks to a request before using privileged repositories or provider services. See [Authenticate a custom route](https://kit.kambium.net/docs/engines.md#authenticate-a-custom-route). |

If you set `retrySafety` on `withClient`, a connection failure can replay the
whole callback. Use `read_only` for a read and `idempotent` only when all effects
in the callback are safe to repeat, including calls outside Postgres. Leave the
option unset for other writes.

Generated for Kit `0.8.0` and Core `0.10.1`.

## Classes

### AirtableService

Airtable operations scoped to an engine connection. In hooks and tasks, use
context.airtable so token recovery and request policy stay on that connection.

#### Constructors

##### Constructor

```ts
new AirtableService(options: 
  | AirtableServiceOptions
  | ConfiguredAirtableServiceOptions
  | AirtableServiceReuseOptions): AirtableService;
```

#### Methods

##### bulkCreateRecords()

```ts
bulkCreateRecords(
   baseId: string, 
   tableId: string, 
   records: {
  fields: Record<string, unknown>;
}[]
): Promise<AirtableListRecordsResponse>;
```

##### bulkUpdateRecords()

```ts
bulkUpdateRecords(
   baseId: string, 
   tableId: string, 
   records: object[]
): Promise<any>;
```

##### createComment()

```ts
createComment(
   baseId: string, 
   tableId: string, 
   recordId: string, 
   text: string
): Promise<any>;
```

##### createField()

```ts
createField(
   baseId: string, 
   tableId: string, 
   field: AirtableMetadataFieldInput
): Promise<any>;
```

##### createRecord()

```ts
createRecord(
   baseId: string, 
   tableId: string, 
   data: Record<string, any>
): Promise<AirtableRecordResponse>;
```

Create a new record. Repeating the request can create another record.

##### createTable()

```ts
createTable(baseId: string, table: AirtableMetadataTableInput): Promise<any>;
```

##### createWebhook()

```ts
createWebhook(baseId: string, options: WebhookOptions): Promise<DirectWebhookInfo>;
```

##### deleteRecord()

```ts
deleteRecord(
   baseId: string, 
   tableId: string, 
   recordId: string
): Promise<void>;
```

##### deleteWebhook()

```ts
deleteWebhook(baseId: string, webhookId: string): Promise<void>;
```

##### enableWebhookNotifications()

```ts
enableWebhookNotifications(baseId: string, webhookId: string): Promise<any>;
```

##### fetch()

```ts
fetch(path: string, params?: AirtableRequestParams): Promise<Response>;
```

##### fetchRecord()

```ts
fetchRecord(
   baseId: string, 
   tableId: string, 
   recordId: string
): Promise<AirtableRecordResponse>;
```

Fetch one record with JSON cell values keyed by field ID.

##### fetchWebhookPayloads()

```ts
fetchWebhookPayloads(
   baseId: string, 
   webhookId: string, 
   cursor: number | undefined
): Promise<AirtableWebhookPayloadsResponse>;
```

##### findRecordsByIds()

```ts
findRecordsByIds(
   baseId: string, 
   tableId: string, 
   recordIds: string[], 
   options?: object
): Promise<AirtableListRecordsResponse>;
```

##### findRecordsByPrimaryFieldValues()

```ts
findRecordsByPrimaryFieldValues(
   baseId: string, 
   tableId: string, 
   primaryFieldName: string, 
   values: string[], 
   options?: {
  maxRecords?: number;
}
): Promise<AirtableListRecordsResponse>;
```

##### getAccessToken()

```ts
getAccessToken(refresh?: boolean): Promise<string>;
```

##### getAccount()

```ts
getAccount(refresh?: boolean): Promise<Account>;
```

##### getBaseTables()

```ts
getBaseTables(baseId: string): Promise<AirtableSchemaResponse>;
```

##### listRecords()

```ts
listRecords(
   baseId: string, 
   tableId: string, 
   options?: AirtableListRecordsOptions
): Promise<AirtableListRecordsResponse>;
```

Fetch one page of records with fields keyed by ID. Supply the response offset
to continue paging, and pass a signal to cancel the request.

##### listWebhooks()

```ts
listWebhooks(baseId: string): Promise<AirtableWebhookListResponse>;
```

##### queryRecords()

```ts
queryRecords(
   baseId: string, 
   tableId: string, 
   options: AirtableQueryRecordsOptions
): Promise<{
  hasMore: boolean;
  records: AirtableRecordResponse[];
}>;
```

Collect a bounded query across provider pages; hasMore distinguishes truncation from exhaustion.

##### refreshWebhook()

```ts
refreshWebhook(baseId: string, webhookId: string): Promise<{
  cursorForNextPayload: string;
  expirationTime: string;
  secret: string;
}>;
```

##### request()

```ts
request(path: string, params?: AirtableRequestParams): Promise<any>;
```

##### updateField()

```ts
updateField(
   baseId: string, 
   tableId: string, 
   fieldId: string, 
   field: object
): Promise<any>;
```

##### updateRecord()

```ts
updateRecord(
   baseId: string, 
   tableId: string, 
   recordId: string, 
   data: Record<string, any>
): Promise<AirtableRecordResponse>;
```

Patch fields on an existing record. Airtable may return field names in the response.

##### withRequestExpiration()

```ts
withRequestExpiration(requestExpirationMs: number): AirtableService;
```

#### Properties

| Property | Modifier | Type |
| ------ | ------ | ------ |
| <a id="property-client"></a> `client` | `protected readonly` | `object` |
| `client.fetch?` | `public` | (`path`: `string`, `params?`: `AirtableRequestParams`) => `Promise`<`Response`> |
| `client.request` | `public` | (`path`: `string`, `params?`: `AirtableRequestParams`) => `Promise`<`any`> |
| <a id="property-log"></a> `log` | `protected readonly` | `EngineLogger` |

***

### CredentialService

#### Constructors

##### Constructor

```ts
new CredentialService(params: object): CredentialService;
```

#### Methods

##### decrypt()

```ts
decrypt(
   encryptedKey: string, 
   ivBase64: string, 
   version: string
): string;
```

##### encrypt()

```ts
encrypt(plaintext: string): object;
```

##### getKey()

```ts
getKey(params: CredentialKeyParams): Promise<CredentialValue | null>;
```

Return the latest matching credential as plaintext or null when absent. Avoid logging the value.

##### storeKey()

```ts
storeKey(params: CredentialKeyParams & object): Promise<void>;
```

Encrypt and upsert a secret for the supplied engine, user, platform and key type.

##### storeKeys()

```ts
storeKeys(entries: object[]): Promise<void>;
```

***

### ExternalPostgresConnectionService

#### Accessors

##### connectionIdentity

###### Get Signature

```ts
get connectionIdentity(): object;
```

Opaque pool-generation identity for engine-owned readiness caches.

#### Constructors

##### Constructor

```ts
new ExternalPostgresConnectionService(connectionString: string, options?: ExternalPostgresConnectionOptions): ExternalPostgresConnectionService;
```

#### Methods

##### checkConnectivity()

```ts
checkConnectivity(): Promise<void>;
```

##### getClientConfig()

```ts
getClientConfig(): ClientConfig & {
  replication?: string;
};
```

For SDKs which create their own client; retains validated DNS pinning and TLS.

##### warmConnection()

```ts
warmConnection(): Promise<void>;
```

##### withClient()

```ts
withClient<T>(
   run: (client: Client) => Promise<T>, 
   options?: ExternalPostgresExecutorOptions, 
   operationPhase?: string
): Promise<T>;
```

Borrow a connection for the callback. Finish all work inside the callback
and let the service release the connection. Use an explicit transaction
for multiple statements that must commit together.

##### closeAllConnections()

```ts
static closeAllConnections(owner?: object): Promise<void>;
```

##### closeIdleConnections()

```ts
static closeIdleConnections(maxIdleMs: number): Promise<void>;
```

##### forEngine()

```ts
static forEngine(__namedParameters: object & Omit<ExternalPostgresConnectionOptions, "resolvedAddress">): Promise<ExternalPostgresConnectionService>;
```

##### hasActivePool()

```ts
static hasActivePool(connectionString: string, owner?: object): boolean;
```

#### Properties

| Property | Modifier | Type |
| ------ | ------ | ------ |
| <a id="property-connectionstring"></a> `connectionString` | `readonly` | `string` |
| <a id="property-log-1"></a> `log?` | `readonly` | `EngineLogger` |

***

### LlmService

#### Constructors

##### Constructor

```ts
new LlmService(dependencies: LlmServiceDependencies): LlmService;
```

#### Methods

##### createAssistantDebugTrace()

```ts
createAssistantDebugTrace(params: Omit<Parameters<typeof createAssistantDebugTrace>[0], "enabled" | "retentionLimit">): AssistantDebugTrace | null;
```

##### runAgent()

```ts
runAgent<Tools extends ToolSet, GeneratedOutput extends Output<any, any, any> = Output<string, string, never>>(input: AgentCoreInput<Tools, GeneratedOutput>): StreamTextResult<Tools, Record<string, unknown>, GeneratedOutput>;
```

Start an agent with the caller's tools and streaming options.

##### runAgentPrompt()

```ts
runAgentPrompt<Tools extends ToolSet, GeneratedOutput extends Output<any, any, any>>(input: Omit<(LanguageModelCallOptions & (RequestOptions<Tools> & Prompt)) & { tools?: Tools | undefined; } & ToolsContextSettings<Tools> & object, "model" | "stopWhen"> & object & Pick<RunStructuredPromptInput, 
  | "log"
  | "syncId"
  | "signal"
  | "systemPrompt"
  | "userPrompt"
  | "outputJsonSchema"
  | "schemaName"
  | "debugNamespace"
  | "debugFilePrefix">): Promise<{
  data: Awaited<InferCompleteOutput<GeneratedOutput>>;
  finishReason: FinishReason;
  providerRequestId: string;
  usage: LanguageModelUsage;
}>;
```

Agent steps use the same debug files as structured prompts, including tool inputs/results.

##### runStructuredPrompt()

```ts
runStructuredPrompt<T = unknown>(input: RunStructuredPromptInput): Promise<RunStructuredPromptResult<T>>;
```

Run a bounded prompt with the supplied JSON schema. Omitted provider and
model use host defaults. Parse the returned data against the application's
schema before relying on application-specific invariants.

***

### PowerService

Shares the engine record and lazy provider clients within one operation.
Prefer the configured EngineContext services inside an engine hook.

#### Accessors

##### airtable

###### Get Signature

```ts
get airtable(): AirtableService;
```

##### slack

###### Get Signature

```ts
get slack(): SlackService;
```

#### Constructors

##### Constructor

```ts
new PowerService<Logger extends EngineLogger & object & object = PowerLogger>(options: object, reuseFrom?: PowerService<Logger>): PowerService<Logger>;
```

#### Methods

##### airtableFetch()

```ts
airtableFetch(path: string, params?: AirtableRequestParams): Promise<Response>;
```

##### airtableRequest()

```ts
airtableRequest(path: string, params?: AirtableRequestParams): Promise<any>;
```

##### getAirtableAccessToken()

```ts
getAirtableAccessToken(refresh?: boolean): Promise<string>;
```

##### getSlackAccessToken()

```ts
getSlackAccessToken(options: {
  refresh?: boolean;
}): Promise<string>;
```

##### getSync()

```ts
getSync(refresh?: boolean): Promise<SyncRecord>;
```

##### slackRequest()

```ts
slackRequest(endpoint: string, options?: SlackRequestParams): Promise<any>;
```

##### updateSyncConfig()

```ts
updateSyncConfig(config: SyncConfig | null): Promise<void>;
```

##### withAirtableRequestExpiration()

```ts
withAirtableRequestExpiration(requestExpirationMs: number): PowerService<Logger>;
```

#### Properties

| Property | Modifier | Type |
| ------ | ------ | ------ |
| <a id="property-log-2"></a> `log` | `readonly` | `Logger` |
| <a id="property-syncid"></a> `syncId` | `readonly` | `string` |

***

### SchemaCacheService

#### Constructors

##### Constructor

```ts
new SchemaCacheService(input: object): SchemaCacheService;
```

#### Methods

##### applyFullSchemaTables()

```ts
applyFullSchemaTables(tables: any[], opts?: {
  pruneMissing?: boolean;
}): Promise<void>;
```

##### getCachedSchemaIndex()

```ts
getCachedSchemaIndex(): Promise<SchemaIndex | undefined>;
```

Read schema metadata from Redis only; a miss must not fetch Airtable.

##### getField()

```ts
getField(tableId: string, fieldId: string): Field | undefined;
```

##### getFieldName()

```ts
getFieldName(tableId: string, fieldId: string): string;
```

##### getFieldOptions()

```ts
getFieldOptions(tableId: string, fieldId: string): any;
```

##### getFields()

```ts
getFields(tableId: string): Field[];
```

##### getFieldType()

```ts
getFieldType(tableId: string, fieldId: string): FieldType;
```

##### getFieldVersions()

```ts
getFieldVersions(tableId: string, fieldId: string): object;
```

Expose field versions for diffing (per-table snapshots).

##### getPrimaryFieldId()

```ts
getPrimaryFieldId(tableId: string): string | undefined;
```

##### getSchema()

```ts
getSchema(opts?: object): Promise<SchemaCache>;
```

Read the selected base schema, or one table when tableId is supplied.
forceRefresh requests fresh metadata rather than using the current cache.

##### getSchemaIndex()

```ts
getSchemaIndex(opts?: object): Promise<SchemaIndex>;
```

Read the full base's metadata index, warming it on a cache miss.

##### getTableName()

```ts
getTableName(tableId: string): string;
```

##### patchSchemaFromDiff()

```ts
patchSchemaFromDiff(diff: SchemaDiff): Promise<void>;
```

Patch the cached FULL schema with info coming from a webhook diff.

##### refreshSchema()

```ts
refreshSchema(opts?: object): Promise<SchemaRefreshSummary>;
```

Refresh and publish the schema without reconstructing every table in memory.

##### snapshotPrevious()

```ts
snapshotPrevious(tableIds: string[]): Promise<void>;
```

Capture a deep snapshot of specific tables into prevCache.
Call this BEFORE mutating via patchSchemaFromDiff.

***

### SlackService

Slack operations for the current engine connection. Use context.slack inside
an engine hook to reuse its configured client and request limits.

#### Constructors

##### Constructor

```ts
new SlackService(options: SlackServiceOptions | ConfiguredSlackServiceOptions): SlackService;
```

#### Methods

##### addReaction()

```ts
addReaction(__namedParameters: object): Promise<void>;
```

##### completeUploadExternal()

```ts
completeUploadExternal(files: SlackUploadFile[]): Promise<{
  file?: {
     id?: string;
  };
  files?: {
     id?: string;
  }[];
}>;
```

##### createMessage()

```ts
createMessage<Block extends object = Record<string, unknown>>(__namedParameters: object): Promise<{
  channel: string;
  ts: string;
}>;
```

Post with the current connection. Omit the channel to use the configured
default, or pass threadTs to reply to an existing message. Retain the returned
channel and timestamp to update the message or route replies.

##### ensureChannelAccess()

```ts
ensureChannelAccess(channelId: string, __namedParameters: object): Promise<SlackChannelAccess>;
```

Report membership; joining public channels is an explicit caller choice.

##### fetchFile()

```ts
fetchFile(url: string, signal?: AbortSignal): Promise<Response>;
```

##### getAccessToken()

```ts
getAccessToken(options?: {
  refresh?: boolean;
}): Promise<string>;
```

##### getChannelName()

```ts
getChannelName(channel: string): Promise<string | null>;
```

##### getConversationInfo()

```ts
getConversationInfo(channel: string, __namedParameters?: {
  signal?: AbortSignal;
}): Promise<SlackConversationInfo>;
```

##### getFileInfo()

```ts
getFileInfo(fileId: string): Promise<SlackFileInfo>;
```

##### getThreadMessagesBefore()

```ts
getThreadMessagesBefore(__namedParameters: object): Promise<SlackThreadMessage[]>;
```

Read thread history before the supplied cutoff timestamp.

##### getUser()

```ts
getUser(userId: string): Promise<{
  email?: string;
  id: string;
  label: string;
  name: string;
  realName?: string;
}>;
```

##### getUserLabel()

```ts
getUserLabel(userId: string): Promise<string>;
```

##### joinConversation()

```ts
joinConversation(channel: string, __namedParameters?: {
  signal?: AbortSignal;
}): Promise<{
  channel: SlackConversationInfo;
  warning?: string;
}>;
```

##### listConversations()

```ts
listConversations(__namedParameters: object): Promise<{
  channels: SlackConversationInfo[];
  nextCursor?: string;
}>;
```

##### openView()

###### Call Signature

```ts
openView<View extends object>(
   triggerId: string, 
   load: SlackViewLoader<View>, 
   options: SlackViewLoadOptions
): Promise<SlackViewResponse>;
```

###### Call Signature

```ts
openView<View extends object>(
   triggerId: string, 
   view: View, 
   options?: {
  signal?: AbortSignal;
}
): Promise<SlackViewResponse>;
```

##### removeReaction()

```ts
removeReaction(__namedParameters: object): Promise<void>;
```

##### request()

```ts
request<Response>(endpoint: string, options?: SlackRequestOptions): Promise<Response>;
```

##### resolveChannelId()

```ts
resolveChannelId(value: string, __namedParameters?: {
  signal?: AbortSignal;
}): Promise<string | null>;
```

IDs pass through; names search the active channels visible to this connection.

##### setThreadStatus()

```ts
setThreadStatus(__namedParameters: object): Promise<{
  ok: boolean;
  warning?: string;
}>;
```

##### updateMessage()

```ts
updateMessage<Block extends object = Record<string, unknown>>(__namedParameters: object): Promise<{
  channel: string;
  ts: string;
}>;
```

Update a posted message using its timestamp and the original channel.

##### updateView()

```ts
updateView<View extends object>(
   viewId: string, 
   hash: string, 
   view: View, 
   options?: {
  signal?: AbortSignal;
}
): Promise<SlackViewResponse>;
```

## Interfaces

### AuthService

#### Methods

##### canAccessEngine()

```ts
canAccessEngine(sync: string | EngineAccessRecord, params?: GetUserParams): Promise<boolean>;
```

Check this caller's access to the engine. Enforce write policy separately.

##### findUserById()

```ts
findUserById(userId: string): Promise<User | null>;
```

##### forVerifiedUser()

```ts
forVerifiedUser(user: User): AuthService;
```

Trusted server-only binding after validating an MCP credential; never a bearer-token fallback.

##### getTokenFromHeader()

```ts
getTokenFromHeader(request: AuthRequest): string;
```

##### getUser()

```ts
getUser(params?: GetUserParams): Promise<User | null>;
```

##### getUserClaims()

```ts
getUserClaims(params?: GetUserParams): Promise<UserClaims | null>;
```

Verify the bearer credential and return its authenticated subject.

##### validateAdminToken()

```ts
validateAdminToken(request: AuthRequest): void;
```

## Type Aliases

### AirtableListRecordsOptions

```ts
type AirtableListRecordsOptions = {
  fields?: string[];
  filterByFormula?: string;
  maxRecords?: number;
  offset?: string;
  pageSize?: number;
  signal?: AbortSignal;
  sort?: object;
};
```

Provider pagination, projection, and filter options for one Airtable page.
Use the returned offset to request the next page.

#### Properties

##### fields?

```ts
fields?: string[];
```

##### filterByFormula?

```ts
filterByFormula?: string;
```

##### maxRecords?

```ts
maxRecords?: number;
```

##### offset?

```ts
offset?: string;
```

##### pageSize?

```ts
pageSize?: number;
```

##### signal?

```ts
signal?: AbortSignal;
```

##### sort?

```ts
sort?: object;
```

###### direction

```ts
direction: "asc" | "desc";
```

###### field

```ts
field: string;
```

***

### AirtableQueryRecordsOptions

```ts
type AirtableQueryRecordsOptions = Omit<AirtableListRecordsOptions, "maxRecords" | "pageSize" | "offset"> & {
  limit: number;
};
```

A bounded query that follows Airtable offsets internally.

#### Type Declaration

##### limit

```ts
limit: number;
```

***

### ExternalPostgresExecutorOptions

```ts
type ExternalPostgresExecutorOptions = {
  retrySafety?: "read_only" | "idempotent";
  signal?: AbortSignal;
};
```

#### Properties

##### retrySafety?

```ts
retrySafety?: "read_only" | "idempotent";
```

##### signal?

```ts
signal?: AbortSignal;
```

***

### LlmProvider

```ts
type LlmProvider = "gemini" | "mistral" | "openai" | "vertex" | "xai";
```

***

### RunStructuredPromptInput

```ts
type RunStructuredPromptInput = {
  debugFilePrefix?: string;
  debugNamespace?: string;
  log: LlmLogger;
  maxOutputTokens?: number;
  model?: string;
  openAiReasoningEffort?: OpenAiReasoningEffort;
  outputJsonSchema: Record<string, unknown>;
  provider?: LlmProvider;
  schemaName?: string;
  schemaStrict?: boolean;
  signal?: AbortSignal;
  store?: boolean;
  syncId: string;
  systemPrompt: string;
  userPrompt: string;
};
```

#### Properties

##### debugFilePrefix?

```ts
debugFilePrefix?: string;
```

##### debugNamespace?

```ts
debugNamespace?: string;
```

##### log

```ts
log: LlmLogger;
```

##### maxOutputTokens?

```ts
maxOutputTokens?: number;
```

##### model?

```ts
model?: string;
```

##### openAiReasoningEffort?

```ts
openAiReasoningEffort?: OpenAiReasoningEffort;
```

##### outputJsonSchema

```ts
outputJsonSchema: Record<string, unknown>;
```

##### provider?

```ts
provider?: LlmProvider;
```

##### schemaName?

```ts
schemaName?: string;
```

##### schemaStrict?

```ts
schemaStrict?: boolean;
```

##### signal?

```ts
signal?: AbortSignal;
```

##### store?

```ts
store?: boolean;
```

##### syncId

```ts
syncId: string;
```

##### systemPrompt

```ts
systemPrompt: string;
```

##### userPrompt

```ts
userPrompt: string;
```

***

### RunStructuredPromptResult

```ts
type RunStructuredPromptResult<T = unknown> = {
  data: T;
  finishReason?: string | null;
  providerRequestId?: string;
  usage?: AiActionUsage;
};
```

#### Properties

##### data

```ts
data: T;
```

##### finishReason?

```ts
finishReason?: string | null;
```

##### providerRequestId?

```ts
providerRequestId?: string;
```

##### usage?

```ts
usage?: AiActionUsage;
```
