Files
PaperClipAI/packages/db/src/schema/tool_access.ts
T
DottaandClaude Opus 5.5 f4cb69205e Let plugin workers serve connector tools (plugin transport) (#22019)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins can now add connector types to the Connectors catalog
(#22004), but only for transports the host already runs (remote MCP,
local stdio)
> - A plugin cannot yet serve a connector's tools itself, and legacy
plugin tools (top-level manifest `tools`) still reach every agent
without a connection or install
> - A plugin should be able to ship a full connector: settings,
credentials, tools, grants, policies and audit, like a built-in one
> - This pull request adds the `plugin` transport, the SDK API to serve
it, and moves legacy plugin tools under the same activation rules
without changing today's access
> - The benefit is that any connector can live in a plugin, and agents
get plugin tools only when an operator enables them

## Linked Issues or Issue Description

Refs #22004

**Subsystem affected**
Plugins (SDK, worker protocol, manifest), Connectors (tool access,
catalog discovery), tool gateway, database.

**Problem or motivation**
A plugin connector can only describe an existing transport. There is no
way for a plugin worker to serve a connector's tools with per-connection
settings and credentials. Legacy plugin tools are visible to every agent
as soon as the plugin is enabled, which is the opposite of the connector
activation rules.

**Proposed solution**
Add a `plugin` transport. The gateway keeps every decision (grant,
policy, approval, rate limit, audit) and calls the plugin worker with
the connection, its settings and a per-call credential. Legacy top-level
tools become one implicit connector per plugin. Existing installations
keep exactly their current access through a one-time migration.

**Alternatives considered**
Move legacy tools to connection tool names (`app.<connection>:<tool>`).
Rejected: names change, so existing tool policies and agent instructions
that name `plugin:tool` would stop matching (a possible widening or
loss). Legacy tools keep their names and handlers; only their visibility
is now gated by an install of the implicit connector.

## What Changed

- `packages/db`: migration `0491` widens
`tool_connections_transport_check` with `plugin` (`NOT VALID`, annotated
`online_compatible`), and adds `plugin_connector_legacy_access`, seeded
with one row per installed legacy-tools plugin and company.
- `packages/shared`: method schema gains `settingsSchema` and `tools`
(`{ kind: "static", list: [{ name, displayName?, description?, risk,
parametersSchema }] } | { kind: "dynamic" }`), only for `transport:
"plugin"`; tool names must match `[a-z0-9_]`; plugin-served methods use
`none` or `api_key`. The connect API accepts `settings`.
- `packages/plugins/sdk`: `ToolRunContext.connection` (`id`, `appSlug`,
`methodKey`, `grantId`, `settings`, `credential?`);
`ctx.connectors.register(appSlug, toolName, fn)` and
`ctx.connectors.listTools(appSlug, fn)`; new `listConnectorTools` RPC;
`executeTool` routes connector calls by `appSlug`. A worker refuses to
start when a declared static tool (or dynamic lister) has no handler.
The test harness gains `executeConnectorTool` and `listConnectorTools`.
- `server/src/services/plugin-connector-runtime.ts`: routes one call to
the plugin's worker; a stopped worker is a
`PluginWorkerUnavailableError`.
- Connect flow (`tool-access.ts`): a `plugin` method creates a
`paperclip_plugin` application and a `plugin` connection with `config =
{ sourceTemplateKey, connectionMethodKey, settings }`, validated against
`settingsSchema`. Credentials, grants, credential policy, installs and
profiles use the existing code.
- Catalog: static tools come from the definition, dynamic tools from
`listConnectorTools`, with the existing version hashing and retirement.
Tool risk comes from the declaration.
- Gateway: plugin connections join connected-tool discovery and both
execution paths (direct and approved actions). For each call the gateway
resolves the grant and, for `api_key`, the credential for that call
only. The run context comes only from the session. A stopped worker
returns `503 plugin_connector_unavailable` with `retryable: true`. The
token broker refuses to export plugin connector credentials.
- Legacy tools: a plugin with top-level `tools` and no `apps` gets an
implicit connector (slug `default`, named after the plugin, no
authentication). Its tools keep their names, handlers and today's access
decision, and an agent sees them only when a connection of that
connector is installed for it or for the company. The connector's saved
action rules (Off, Ask first) can only restrict them.
`completeLegacyPluginToolAccess` turns each migration row into such a
connection with a company install, at boot and when a disabled plugin is
enabled again; it is single-flight across servers, resumes a draft left
by an interrupted attempt, and never overrides an operator's later
changes.
- Catalog: tools a dynamic connector stops offering are retired from
discovery; `listConnectorTools` carries the connection's `companyId`,
and uses the acting person's grant for personal connections.
- Board: the setup flow renders `settingsSchema` with the shared JSON
Schema form, sends `settings`, and restores saved settings on resume and
reconnect.
- `create-paperclip-plugin --template connector` now scaffolds a plugin
connector (`apps` + `ctx.connectors.register` + a harness test). SDK
README and `PLUGIN_SPEC.md` describe connectors; top-level `tools` stay
documented as legacy.
- `inferToolRisk` moves to `tool-risk-inference.ts` so the catalog can
reuse it.

Design notes where the spec left room:
- OAuth for `plugin`-transport methods is not supported in this PR
(`none` and `api_key` only); OAuth plugin connectors can use
`mcp_remote` today. Noted as follow-up.
- Board "Test" calls on a plugin connection pass an empty
`agentId`/`runId`, because there is no agent run.
- Companies created after the upgrade get no automatic legacy
connection; they follow the normal activation rules.

## Verification

- `server`: `npx vitest run
src/__tests__/plugin-connectors-plugin-transport.test.ts` (new):
- rules 1-3: a ready plugin and configured accounts give no tools; an
install for agent A gives only A the tools; agent B is denied on
invocation;
- the worker receives `runContext.connection` with the right id, method,
grant, settings and the call's credential; spoofed arguments do not
change it; each account calls with its own key; results do not contain
the key;
- invalid settings are rejected (422); a stopped worker is `503
plugin_connector_unavailable` (retryable); a disabled plugin hides the
tools;
- dynamic tools are listed through the worker and a tool it stops
offering is retired;
- rule 5: a new installation of a legacy-tools plugin gives no tools; an
installation recorded by the migration keeps the same tool names for
every agent, through one company-wide connection (two concurrent
carry-overs make one; an interrupted draft is finished; a retry keeps an
operator's restriction), and is not also exposed as connection tools;
Ask first and Off on the implicit connector restrict the legacy tools;
  - the token broker refuses to export a plugin connection's credential.
- Existing gateway plugin-tool tests (`tool-gateway`,
`tool-gateway-service`, `prompt-injection-gateway`) now set up the
legacy grant an existing installation has, and pass unchanged otherwise.
- Regression: `plugin-connectors-circleback-parity`, `tool-gateway`,
`tool-gateway-service`, `prompt-injection-gateway`,
`tool-access-service` (846 passed), plus `connector-tool-policy`,
`plugin-lifecycle-restart`, `remote-mcp-connectors`,
`ai-connection-router` in an earlier run.
- UI: `AppsConnect.test.tsx` covers sending plugin settings from the
settings schema.
- SDK: `tests/worker-rpc-host.test.ts` (start refusal without handlers,
connector routing, tool listing). Scaffold: `entrypoints.test.ts`.
- `packages/db`: `pnpm typecheck` including `check:migrations`; server
layered typecheck (sources and tests); `tsc --noEmit` for shared, SDK,
scaffold and UI.

## Risks

- Behavior change for new installations: legacy plugin tools no longer
reach agents until an operator connects the plugin's connector.
Installations that exist at upgrade time keep their tools through the
migration rows.
- The migration widens a check constraint (`NOT VALID`) and copies
plugin × company rows into a new table. Both are fast; the previous
release never writes `plugin`.
- Calls depend on the plugin worker; when it is down the agent gets a
retryable error.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file editing, test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:09:42 +00:00

1254 lines
69 KiB
TypeScript

import {
sql,
} from "drizzle-orm";
import {
boolean,
check,
foreignKey,
index,
integer,
jsonb,
pgTable,
text,
timestamp,
unique,
uniqueIndex,
uuid,
} from "drizzle-orm/pg-core";
import type {
ToolCallProgress,
ConnectionAgentInstructions,
ConnectionTokenIssuanceOutcome,
ConnectionTokenIssuancePath,
McpAppModelContext,
McpAppToolUi,
McpIcon,
McpConnectionCredentialRef,
ToolActionRequestStatus,
ToolApplicationStatus,
ToolApplicationType,
ToolAuditEventType,
ToolAuditOutcome,
ToolCatalogEntryKind,
ToolCatalogEntryStatus,
ToolConnectionHealthStatus,
ToolConnectionAuthKind,
ToolConnectionCredentialSource,
ToolConnectionKind,
ToolConnectionCredentialPolicy,
ToolConnectionOwnership,
ToolConnectionPurpose,
ToolConnectionInstallTargetType,
ToolConnectionStatus,
ToolConnectionTransport,
ConnectionGrantKind,
ConnectionGrantMemberSubjectType,
ConnectionGrantStatus,
ToolCredentialSecretRef,
ToolInvocationApprovalState,
ToolInvocationStatus,
ToolMcpGatewayAuthConfig,
ToolMcpGatewayContextScopeType,
ToolMcpGatewayDefaultProfileMode,
ToolMcpGatewayHeaderPolicy,
ToolMcpGatewayMetadataPolicy,
ToolMcpGatewayOnDemandToolsConfig,
ToolMcpGatewayStatus,
ToolMcpGatewayTokenAction,
ToolMcpGatewayTokenSubjectType,
ToolPolicyDecision,
ToolPolicyType,
ToolProfileBindingTargetType,
ToolProfileDefaultAction,
ToolProfileEntryEffect,
ToolProfileEntrySelectorType,
ToolProfileStatus,
ToolRateLimitWindowKind,
ToolRedactedValueSummary,
ToolRiskLevel,
ToolRuntimeKind,
ToolRuntimeSlotStatus,
VercelConnectCredentialReference,
VercelConnectGrantReference,
} from "@paperclipai/shared";
import { agents } from "./agents.js";
import { approvals } from "./approvals.js";
import { companies } from "./companies.js";
import { executionWorkspaces } from "./execution_workspaces.js";
import { heartbeatRuns } from "./heartbeat_runs.js";
import { issueThreadInteractions } from "./issue_thread_interactions.js";
import { issues } from "./issues.js";
import { plugins } from "./plugins.js";
import { projects } from "./projects.js";
import { projectWorkspaces } from "./project_workspaces.js";
export const toolApplications = pgTable(
"tool_applications",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
applicationKey: text("application_key"),
name: text("name").notNull(),
description: text("description"),
type: text("type").$type<ToolApplicationType>().notNull(),
status: text("status").$type<ToolApplicationStatus>().notNull().default("active"),
pluginId: uuid("plugin_id").references(() => plugins.id, { onDelete: "set null" }),
ownerAgentId: uuid("owner_agent_id").references(() => agents.id, { onDelete: "set null" }),
ownerUserId: text("owner_user_id"),
metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
archivedAt: timestamp("archived_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_applications_company_idx").on(table.companyId),
index("tool_applications_company_status_idx").on(table.companyId, table.status),
uniqueIndex("tool_applications_company_name_uq").on(table.companyId, table.name),
uniqueIndex("tool_applications_company_key_uq").on(table.companyId, table.applicationKey),
],
);
export const toolConnections = pgTable(
"tool_connections",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
// NO ACTION (not CASCADE) so the database itself refuses to delete an application that still
// has connections. This closes the delete-vs-create race in DELETE
// /tool-applications/:applicationId: a connection inserted concurrently takes a FOR KEY SHARE
// lock on the parent row, so the delete fails closed with a foreign-key violation instead of
// silently cascading the new connection away. NO ACTION (checked at end-of-statement) rather
// than RESTRICT (checked immediately) is deliberate: it lets a company delete still cascade —
// companies → tool_applications and companies → tool_connections both fire in one statement,
// and the connections are gone by the time this constraint is checked.
applicationId: uuid("application_id").notNull().references(() => toolApplications.id, { onDelete: "no action" }),
name: text("name").notNull(),
uid: text("uid").notNull(),
connectionKind: text("connection_kind").$type<ToolConnectionKind>().notNull().default("managed"),
connectionPurpose: text("connection_purpose").$type<ToolConnectionPurpose>().notNull().default("tool"),
ownership: text("ownership").$type<ToolConnectionOwnership>().notNull().default("customer"),
transport: text("transport").$type<ToolConnectionTransport>().notNull(),
authKind: text("auth_kind").$type<ToolConnectionAuthKind>().notNull().default("none"),
credentialSource: text("credential_source").$type<ToolConnectionCredentialSource>().notNull().default("paperclip_vault"),
externalCredential: jsonb("external_credential").$type<VercelConnectCredentialReference>(),
credentialPolicy: text("credential_policy").$type<ToolConnectionCredentialPolicy>().notNull().default("shared"),
status: text("status").$type<ToolConnectionStatus>().notNull().default("draft"),
enabled: boolean("enabled").notNull().default(false),
agentInstructions: jsonb("agent_instructions").$type<ConnectionAgentInstructions>(),
config: jsonb("config").$type<Record<string, unknown>>().notNull().default({}),
transportConfig: jsonb("transport_config").$type<Record<string, unknown>>().notNull().default({}),
credentialRefs: jsonb("credential_refs").$type<McpConnectionCredentialRef[]>().notNull().default([]),
credentialSecretRefs: jsonb("credential_secret_refs").$type<ToolCredentialSecretRef[]>().notNull().default([]),
healthStatus: text("health_status").$type<ToolConnectionHealthStatus>().notNull().default("unchecked"),
healthMessage: text("health_message"),
healthCheckedAt: timestamp("health_checked_at", { withTimezone: true }),
lastHealthAt: timestamp("last_health_at", { withTimezone: true }),
lastCatalogRefreshAt: timestamp("last_catalog_refresh_at", { withTimezone: true }),
lastError: text("last_error"),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
check("tool_connections_ownership_check", sql`${table.ownership} in ('platform_shared', 'platform_provisioned', 'customer', 'dcr')`),
check("tool_connections_transport_check", sql`${table.transport} in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'voice', 'runtime_auth', 'plugin')`),
check("tool_connections_purpose_check", sql`${table.connectionPurpose} in ('tool', 'channel', 'ai')`),
check("tool_connections_channel_transport_check", sql`(
(${table.connectionPurpose} = 'tool' and ${table.transport} not in ('chat_sdk', 'voice', 'runtime_auth'))
or
(${table.connectionPurpose} = 'channel' and (${table.transport} in ('chat_sdk', 'voice') or (${table.transport} = 'rest_api' and ${table.config}->>'provider' = 'agentmail')))
or
(${table.connectionPurpose} = 'ai' and ${table.transport} = 'runtime_auth')
)`),
check("tool_connections_auth_kind_check", sql`${table.authKind} in ('oauth', 'api_key', 'none')`),
check("tool_connections_credential_source_check", sql`${table.credentialSource} in ('paperclip_vault', 'vercel_connect')`),
check("tool_connections_credential_source_one_of_check", sql`(
(${table.credentialSource} = 'paperclip_vault' and ${table.externalCredential} is null)
or
(${table.credentialSource} = 'vercel_connect' and ${table.externalCredential} is not null and jsonb_array_length(${table.credentialRefs}) = 0 and jsonb_array_length(${table.credentialSecretRefs}) = 0)
)`),
check("tool_connections_credential_policy_check", sql`${table.credentialPolicy} in ('shared', 'per_user', 'per_user_with_fallback', 'per_agent')`),
index("tool_connections_company_idx").on(table.companyId),
index("tool_connections_application_idx").on(table.applicationId),
index("tool_connections_company_enabled_idx").on(table.companyId, table.enabled),
uniqueIndex("tool_connections_company_uid_uq").on(table.companyId, table.uid),
unique("tool_connections_company_id_uq").on(table.companyId, table.id),
],
);
export const connectionGrants = pgTable(
"connection_grants",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull(),
kind: text("kind").$type<ConnectionGrantKind>().notNull(),
subjectUserId: text("subject_user_id"),
subjectAgentId: uuid("subject_agent_id").references(() => agents.id, { onDelete: "cascade" }),
providerTenant: jsonb("provider_tenant").$type<{
name?: string;
externalId?: string;
oauth?: {
strategy?: string;
accessTokenExpiresAt?: string | null;
scopes?: string[];
/**
* Whether `scopes` is what the provider asserted, or only what we requested.
* A provider may omit `scope` from the token response, and RFC 6749 §5.1 reads that
* omission as "the grant matches the request" — but a provider that over-grants and
* omits it turns our own request into a false record of the grant.
*/
scopeSource?: "provider" | "requested_fallback";
/** Scopes the provider asserted that we never asked for. Empty unless it over-granted. */
unrequestedScopes?: string[];
/**
* The scopes the authorization URL sent for *this* grant. A refresh carries no fresh
* request, so this is the baseline it judges the provider's response against. It is
* per-grant because two users can authorize the same connection with different scopes.
*/
requestedScopes?: string[];
/** Last successful consent; ordinary token refresh preserves this. */
consentedAt?: string;
tokenType?: string;
refreshedAt?: string;
refreshTokenExpiresAt?: string;
refreshLease?: {
id?: string;
expiresAt?: string;
};
};
slackSearch?: { endpointId: string; workspaceId: string; slackUserId: string; clientRevision: string };
github?: {
userId: string;
login: string;
avatarUrl?: string;
installationCount: number;
repositoryCount: number;
repositorySelection: "all" | "selected" | "mixed" | "none";
installationIds: string[];
installationOwnerLogins: string[];
/** Repository metadata visible to this credential; refreshed from GitHub. */
repositories?: Array<{ id: string; fullName: string; installationId: string; private?: boolean }>;
installationUrl?: string;
managementUrl?: string;
appSlug?: string;
accessRevision?: string;
lastAccessRefreshAt?: string;
bindingSync?: { id: string; removeInstallationIds: string[] };
continuityRetry?: { at: string; attempts: number; revision: string };
lastWebhookAt?: string;
webhookHealth?: "pending" | "healthy" | "unhealthy";
};
}>(),
credentialSecretRefs: jsonb("credential_secret_refs").$type<ToolCredentialSecretRef[]>().notNull().default([]),
externalCredential: jsonb("external_credential").$type<VercelConnectGrantReference>(),
status: text("status").$type<ConnectionGrantStatus>().notNull().default("active"),
isDefault: boolean("is_default").notNull().default(false),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
revokedAt: timestamp("revoked_at", { withTimezone: true }),
revokedByAgentId: uuid("revoked_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
revokedByUserId: text("revoked_by_user_id"),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
check("connection_grants_kind_check", sql`${table.kind} in ('organization', 'user', 'agent')`),
check("connection_grants_status_check", sql`${table.status} in ('active', 'revoked', 'expired', 'needs_reauthorization')`),
check("connection_grants_credential_source_one_of_check", sql`${table.externalCredential} is null or jsonb_array_length(${table.credentialSecretRefs}) = 0`),
check("connection_grants_subject_check", sql`(${table.kind} = 'user' and ${table.subjectUserId} is not null and ${table.subjectAgentId} is null) or (${table.kind} = 'agent' and ${table.subjectAgentId} is not null and ${table.subjectUserId} is null) or (${table.kind} = 'organization' and ${table.subjectUserId} is null and ${table.subjectAgentId} is null)`),
check("connection_grants_default_check", sql`${table.isDefault} = false or ${table.kind} = 'organization'`),
foreignKey({
columns: [table.companyId, table.connectionId],
foreignColumns: [toolConnections.companyId, toolConnections.id],
name: "connection_grants_company_connection_fk",
}).onDelete("cascade"),
index("connection_grants_company_connection_idx").on(table.companyId, table.connectionId),
index("connection_grants_subject_user_idx").on(table.companyId, table.subjectUserId),
index("connection_grants_subject_agent_idx").on(table.companyId, table.subjectAgentId),
unique("connection_grants_company_id_uq").on(table.companyId, table.id),
uniqueIndex("connection_grants_user_uq").on(table.connectionId, table.subjectUserId),
uniqueIndex("connection_grants_agent_uq").on(table.connectionId, table.subjectAgentId),
uniqueIndex("connection_grants_default_uq").on(table.connectionId).where(sql`${table.isDefault} = true and ${table.kind} = 'organization'`),
],
);
export const connectionGrantMembers = pgTable(
"connection_grant_members",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
grantId: uuid("grant_id").notNull(),
subjectType: text("subject_type").$type<ConnectionGrantMemberSubjectType>().notNull(),
subjectId: text("subject_id").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
check("connection_grant_members_subject_type_check", sql`${table.subjectType} in ('user')`),
foreignKey({
columns: [table.companyId, table.grantId],
foreignColumns: [connectionGrants.companyId, connectionGrants.id],
name: "connection_grant_members_company_grant_fk",
}).onDelete("cascade"),
index("connection_grant_members_company_subject_idx").on(table.companyId, table.subjectType, table.subjectId),
uniqueIndex("connection_grant_members_grant_subject_uq").on(table.grantId, table.subjectType, table.subjectId),
],
);
export const connectionGrantDelegations = pgTable(
"connection_grant_delegations",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
grantId: uuid("grant_id").notNull(),
agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }),
createdByUserId: text("created_by_user_id").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
foreignKey({
columns: [table.companyId, table.grantId],
foreignColumns: [connectionGrants.companyId, connectionGrants.id],
name: "connection_grant_delegations_company_grant_fk",
}).onDelete("cascade"),
index("connection_grant_delegations_company_agent_idx").on(table.companyId, table.agentId),
uniqueIndex("connection_grant_delegations_grant_agent_uq").on(table.grantId, table.agentId),
],
);
export const toolConnectionInstalls = pgTable(
"tool_connection_installs",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
targetType: text("target_type").$type<ToolConnectionInstallTargetType>().notNull(),
targetId: text("target_id").notNull(),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
check("tool_connection_installs_target_type_check", sql`${table.targetType} in ('company', 'agent')`),
index("tool_connection_installs_company_target_idx").on(table.companyId, table.targetType, table.targetId),
index("tool_connection_installs_connection_idx").on(table.companyId, table.connectionId),
uniqueIndex("tool_connection_installs_target_uq").on(
table.companyId,
table.connectionId,
table.targetType,
table.targetId,
),
],
);
export const toolOauthStates = pgTable(
"tool_oauth_states",
{
state: text("state").primaryKey(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
codeVerifier: text("code_verifier").notNull(),
createdByActorType: text("created_by_actor_type"),
createdByActorId: text("created_by_actor_id"),
createdBySessionId: text("created_by_session_id"),
subjectUserId: text("subject_user_id"),
subjectAgentId: uuid("subject_agent_id").references(() => agents.id, { onDelete: "cascade" }),
requestedScopes: jsonb("requested_scopes").$type<string[]>(),
returnTo: text("return_to"),
issueId: uuid("issue_id"),
interactionId: uuid("interaction_id"),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_oauth_states_company_idx").on(table.companyId),
index("tool_oauth_states_connection_idx").on(table.connectionId),
index("tool_oauth_states_actor_idx").on(table.createdByActorType, table.createdByActorId),
index("tool_oauth_states_subject_agent_idx").on(table.companyId, table.subjectAgentId),
index("tool_oauth_states_expires_at_idx").on(table.expiresAt),
],
);
export const toolCatalogEntries = pgTable(
"tool_catalog_entries",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
applicationId: uuid("application_id").references(() => toolApplications.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
entryKind: text("entry_kind").$type<ToolCatalogEntryKind>().notNull().default("tool"),
name: text("name").notNull(),
toolName: text("tool_name").notNull(),
title: text("title"),
description: text("description"),
inputSchema: jsonb("input_schema").$type<Record<string, unknown>>().notNull().default({}),
outputSchema: jsonb("output_schema").$type<Record<string, unknown>>(),
annotations: jsonb("annotations").$type<Record<string, unknown>>().notNull().default({}),
/** Normalized MCP Apps `_meta.ui` declaration (`ui://` view), when the tool has one. */
uiMeta: jsonb("ui_meta").$type<McpAppToolUi>(),
/** Sanitized MCP `icons` (SEP-973) the provider declared for the tool. Not part of the version hash. */
icons: jsonb("icons").$type<McpIcon[]>(),
riskLevel: text("risk_level").$type<ToolRiskLevel>().notNull().default("read"),
isReadOnly: boolean("is_read_only").notNull().default(true),
isWrite: boolean("is_write").notNull().default(false),
isDestructive: boolean("is_destructive").notNull().default(false),
status: text("status").$type<ToolCatalogEntryStatus>().notNull().default("active"),
version: text("version"),
versionHash: text("version_hash").notNull(),
schemaHash: text("schema_hash"),
firstSeenAt: timestamp("first_seen_at", { withTimezone: true }).notNull().defaultNow(),
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
reviewedByAgentId: uuid("reviewed_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
reviewedByUserId: text("reviewed_by_user_id"),
quarantinedAt: timestamp("quarantined_at", { withTimezone: true }),
quarantineReason: text("quarantine_reason"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_catalog_entries_company_idx").on(table.companyId),
index("tool_catalog_entries_application_idx").on(table.applicationId),
index("tool_catalog_entries_connection_idx").on(table.connectionId),
index("tool_catalog_entries_company_status_idx").on(table.companyId, table.status),
uniqueIndex("tool_catalog_entries_connection_name_uq").on(table.connectionId, table.name),
],
);
export const toolProfiles = pgTable(
"tool_profiles",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
profileKey: text("profile_key").notNull(),
name: text("name").notNull(),
description: text("description"),
status: text("status").$type<ToolProfileStatus>().notNull().default("active"),
defaultAction: text("default_action").$type<ToolProfileDefaultAction>().notNull().default("deny"),
newToolsReviewedAt: timestamp("new_tools_reviewed_at", { withTimezone: true }),
metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_profiles_company_status_idx").on(table.companyId, table.status),
uniqueIndex("tool_profiles_company_key_uq").on(table.companyId, table.profileKey),
uniqueIndex("tool_profiles_company_name_uq").on(table.companyId, table.name),
],
);
export const toolProfileEntries = pgTable(
"tool_profile_entries",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
profileId: uuid("profile_id").notNull().references(() => toolProfiles.id, { onDelete: "cascade" }),
selectorType: text("selector_type").$type<ToolProfileEntrySelectorType>().notNull(),
effect: text("effect").$type<ToolProfileEntryEffect>().notNull().default("include"),
applicationId: uuid("application_id").references(() => toolApplications.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").references(() => toolConnections.id, { onDelete: "cascade" }),
catalogEntryId: uuid("catalog_entry_id").references(() => toolCatalogEntries.id, { onDelete: "cascade" }),
toolName: text("tool_name"),
riskLevel: text("risk_level").$type<ToolRiskLevel>(),
conditions: jsonb("conditions").$type<Record<string, unknown>>(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_profile_entries_company_profile_idx").on(table.companyId, table.profileId),
index("tool_profile_entries_application_idx").on(table.companyId, table.applicationId),
index("tool_profile_entries_connection_idx").on(table.companyId, table.connectionId),
index("tool_profile_entries_catalog_entry_idx").on(table.companyId, table.catalogEntryId),
],
);
export const toolProfileBindings = pgTable(
"tool_profile_bindings",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
profileId: uuid("profile_id").notNull().references(() => toolProfiles.id, { onDelete: "cascade" }),
targetType: text("target_type").$type<ToolProfileBindingTargetType>().notNull(),
targetId: text("target_id").notNull(),
priority: integer("priority").notNull().default(100),
metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_profile_bindings_company_target_idx").on(table.companyId, table.targetType, table.targetId),
uniqueIndex("tool_profile_bindings_target_profile_uq").on(
table.companyId,
table.targetType,
table.targetId,
table.profileId,
),
],
);
export const toolMcpGateways = pgTable(
"tool_mcp_gateways",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
gatewayPublicId: text("gateway_public_id").notNull().default(sql`'gw_' || replace(gen_random_uuid()::text, '-', '')`),
name: text("name").notNull(),
slug: text("slug").notNull(),
displaySlug: text("display_slug").notNull().default(""),
description: text("description"),
status: text("status").$type<ToolMcpGatewayStatus>().notNull().default("active"),
profileId: uuid("profile_id").notNull().references(() => toolProfiles.id, { onDelete: "restrict" }),
defaultProfileMode: text("default_profile_mode").$type<ToolMcpGatewayDefaultProfileMode>().notNull().default("gateway_only"),
contextScopeType: text("context_scope_type").$type<ToolMcpGatewayContextScopeType>().notNull().default("none"),
contextScopeId: text("context_scope_id"),
agentId: uuid("agent_id").references(() => agents.id, { onDelete: "set null" }),
projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
approvalIssueId: uuid("approval_issue_id").references(() => issues.id, { onDelete: "set null" }),
authConfig: jsonb("auth_config").$type<ToolMcpGatewayAuthConfig>().notNull().default({
version: 1,
bearer: {
enabled: true,
tokenPrefix: "pcgw",
defaultTtlSeconds: 7_776_000,
requireFiniteExpiry: true,
longLivedTokenRequiresOverride: true,
},
oauth: {
enabled: false,
reservedFor: "v1_5",
dynamicClientRegistration: false,
authorizationCodePkce: false,
},
}),
headerPolicy: jsonb("header_policy").$type<ToolMcpGatewayHeaderPolicy>().notNull().default({
version: 1,
callerPassthrough: { enabled: false, allowedHeaders: [] },
staticHeaders: [],
generatedMetadata: { enabled: false, allowedHeaders: [] },
responseHeaders: { forwardMcpRequiredHeaders: true, forwardSafeCacheHeaders: true },
}),
metadataPolicy: jsonb("metadata_policy").$type<ToolMcpGatewayMetadataPolicy>().notNull().default({
version: 1,
forwardCompanyId: false,
forwardGatewayId: false,
forwardProjectId: false,
forwardIssueId: false,
forwardAgentId: false,
forwardRunId: false,
forwardCorrelationId: true,
}),
onDemandToolsConfig: jsonb("on_demand_tools_config").$type<ToolMcpGatewayOnDemandToolsConfig>().notNull().default({
enabled: false,
searchToolName: "search_tools",
runToolName: "run_tool",
}),
metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
archivedAt: timestamp("archived_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_mcp_gateways_company_idx").on(table.companyId),
index("tool_mcp_gateways_company_status_idx").on(table.companyId, table.status),
index("tool_mcp_gateways_profile_idx").on(table.companyId, table.profileId),
uniqueIndex("tool_mcp_gateways_public_id_uq").on(table.gatewayPublicId),
uniqueIndex("tool_mcp_gateways_company_slug_uq").on(table.companyId, table.slug),
uniqueIndex("tool_mcp_gateways_company_name_uq").on(table.companyId, table.name),
],
);
export const toolMcpGatewayTokens = pgTable(
"tool_mcp_gateway_tokens",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
gatewayId: uuid("gateway_id").notNull().references(() => toolMcpGateways.id, { onDelete: "cascade" }),
name: text("name").notNull(),
tokenHash: text("token_hash").notNull(),
tokenPrefix: text("token_prefix").notNull().default(""),
subjectType: text("subject_type").$type<ToolMcpGatewayTokenSubjectType>().notNull().default("gateway_client"),
subjectId: text("subject_id"),
clientLabel: text("client_label").notNull().default(""),
// Null distinguishes board/legacy clients from delegated agent clients.
responsibleUserId: text("responsible_user_id"),
ownerNote: text("owner_note").notNull().default(""),
// Agent-created client tokens have no usable value until the responsible
// person reveals one on the gateway's Tokens page; agents never receive it.
pendingReveal: boolean("pending_reveal").notNull().default(false),
allowedActions: jsonb("allowed_actions").$type<ToolMcpGatewayTokenAction[]>().notNull().default(["tools/list", "tools/call"]),
expiresAt: timestamp("expires_at", { withTimezone: true }),
expiryOverrideReason: text("expiry_override_reason"),
expiryOverrideByUserId: text("expiry_override_by_user_id"),
expiryOverrideByAgentId: uuid("expiry_override_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
expiryOverrideAt: timestamp("expiry_override_at", { withTimezone: true }),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
revokedAt: timestamp("revoked_at", { withTimezone: true }),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("tool_mcp_gateway_tokens_token_hash_uq").on(table.tokenHash),
index("tool_mcp_gateway_tokens_expiry_idx").on(table.expiresAt, table.id),
index("tool_mcp_gateway_tokens_gateway_idx").on(table.companyId, table.gatewayId),
index("tool_mcp_gateway_tokens_subject_idx").on(table.companyId, table.subjectType, table.subjectId),
index("tool_mcp_gateway_tokens_company_expires_idx").on(table.companyId, table.expiresAt),
],
);
export const toolPolicies = pgTable(
"tool_policies",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
name: text("name").notNull(),
description: text("description"),
policyType: text("policy_type").$type<ToolPolicyType>().notNull(),
priority: integer("priority").notNull().default(100),
enabled: boolean("enabled").notNull().default(true),
selectors: jsonb("selectors").$type<Record<string, unknown>>().notNull().default({}),
conditions: jsonb("conditions").$type<Record<string, unknown>>(),
config: jsonb("config").$type<Record<string, unknown>>(),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_policies_company_enabled_idx").on(table.companyId, table.enabled),
index("tool_policies_company_type_idx").on(table.companyId, table.policyType),
uniqueIndex("tool_policies_company_name_uq").on(table.companyId, table.name),
],
);
export const toolRuntimeSlots = pgTable(
"tool_runtime_slots",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
applicationId: uuid("application_id").references(() => toolApplications.id, { onDelete: "set null" }),
connectionId: uuid("connection_id").references(() => toolConnections.id, { onDelete: "cascade" }),
projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }),
executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
ownerScopeType: text("owner_scope_type").notNull().default("connection"),
ownerScopeId: text("owner_scope_id"),
runtimeKind: text("runtime_kind").$type<ToolRuntimeKind>().notNull().default("local_stdio"),
slotKey: text("slot_key").notNull(),
status: text("status").$type<ToolRuntimeSlotStatus>().notNull().default("stopped"),
reuseKey: text("reuse_key"),
workspaceScope: text("workspace_scope"),
credentialScopeHash: text("credential_scope_hash"),
provider: text("provider"),
providerRef: text("provider_ref"),
processId: integer("process_id"),
commandTemplateKey: text("command_template_key"),
healthStatus: text("health_status").$type<ToolConnectionHealthStatus>().notNull().default("unchecked"),
healthMessage: text("health_message"),
lastHealthCheckAt: timestamp("last_health_check_at", { withTimezone: true }),
lastStartedAt: timestamp("last_started_at", { withTimezone: true }),
startedAt: timestamp("started_at", { withTimezone: true }),
stoppedAt: timestamp("stopped_at", { withTimezone: true }),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
idleExpiresAt: timestamp("idle_expires_at", { withTimezone: true }),
idleDeadlineAt: timestamp("idle_deadline_at", { withTimezone: true }),
lastError: text("last_error"),
metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_runtime_slots_company_idx").on(table.companyId),
index("tool_runtime_slots_connection_idx").on(table.connectionId),
index("tool_runtime_slots_execution_workspace_idx").on(table.companyId, table.executionWorkspaceId),
uniqueIndex("tool_runtime_slots_slot_key_uq").on(table.companyId, table.slotKey),
],
);
export const toolStdioCommandTemplates = pgTable(
"tool_stdio_command_templates",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
templateKey: text("template_key").notNull(),
name: text("name").notNull(),
description: text("description"),
status: text("status").$type<"active" | "disabled">().notNull().default("active"),
command: text("command").notNull(),
args: jsonb("args").$type<string[]>().notNull().default([]),
envKeys: jsonb("env_keys").$type<string[]>().notNull().default([]),
tools: jsonb("tools").$type<Array<Record<string, unknown>>>().notNull().default([]),
createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
createdByUserId: text("created_by_user_id"),
disabledAt: timestamp("disabled_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_stdio_command_templates_company_idx").on(table.companyId),
index("tool_stdio_command_templates_company_status_idx").on(table.companyId, table.status),
uniqueIndex("tool_stdio_command_templates_company_key_uq").on(table.companyId, table.templateKey),
],
);
export const toolGatewaySessions = pgTable(
"tool_gateway_sessions",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }),
runId: uuid("run_id").notNull().references(() => heartbeatRuns.id, { onDelete: "cascade" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }),
gatewayId: uuid("gateway_id").references(() => toolMcpGateways.id, { onDelete: "set null" }),
gatewayTokenId: uuid("gateway_token_id").references(() => toolMcpGatewayTokens.id, { onDelete: "set null" }),
gatewayPublicId: text("gateway_public_id"),
clientSubjectType: text("client_subject_type").$type<ToolMcpGatewayTokenSubjectType>(),
clientSubjectId: text("client_subject_id"),
clientName: text("client_name"),
mcpSessionId: text("mcp_session_id"),
correlationId: text("correlation_id"),
tokenHash: text("token_hash").notNull(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
revokedAt: timestamp("revoked_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("tool_gateway_sessions_token_hash_uq").on(table.tokenHash),
index("tool_gateway_sessions_company_agent_idx").on(table.companyId, table.agentId),
index("tool_gateway_sessions_company_expires_idx").on(table.companyId, table.expiresAt),
index("tool_gateway_sessions_expiry_idx").on(table.expiresAt),
index("tool_gateway_sessions_run_idx").on(table.companyId, table.runId),
index("tool_gateway_sessions_issue_idx").on(table.companyId, table.issueId),
index("tool_gateway_sessions_gateway_idx").on(table.companyId, table.gatewayId),
],
);
export const toolGatewayRateLimitCounters = pgTable(
"tool_gateway_rate_limit_counters",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
counterKey: text("counter_key").notNull(),
windowStartAt: timestamp("window_start_at", { withTimezone: true }).notNull(),
windowMs: integer("window_ms").notNull(),
limit: integer("limit").notNull(),
count: integer("count").notNull().default(0),
resetAt: timestamp("reset_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_gateway_rate_limit_counters_company_idx").on(table.companyId),
uniqueIndex("tool_gateway_rate_limit_counters_window_uq").on(
table.companyId,
table.counterKey,
table.windowStartAt,
),
],
);
export const toolInvocations = pgTable(
"tool_invocations",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
idempotencyKey: text("idempotency_key"),
actorType: text("actor_type").notNull().default("system"),
actorId: text("actor_id"),
agentId: uuid("agent_id").references(() => agents.id, { onDelete: "set null" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
runId: uuid("run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }),
gatewayId: uuid("gateway_id").references(() => toolMcpGateways.id, { onDelete: "set null" }),
gatewayTokenId: uuid("gateway_token_id").references(() => toolMcpGatewayTokens.id, { onDelete: "set null" }),
gatewayPublicId: text("gateway_public_id"),
clientSubjectType: text("client_subject_type").$type<ToolMcpGatewayTokenSubjectType>(),
clientSubjectId: text("client_subject_id"),
clientName: text("client_name"),
mcpSessionId: text("mcp_session_id"),
correlationId: text("correlation_id"),
applicationId: uuid("application_id").references(() => toolApplications.id, { onDelete: "set null" }),
connectionId: uuid("connection_id").references(() => toolConnections.id, { onDelete: "set null" }),
catalogEntryId: uuid("catalog_entry_id").references(() => toolCatalogEntries.id, { onDelete: "set null" }),
catalogVersionHash: text("catalog_version_hash"),
catalogSchemaHash: text("catalog_schema_hash"),
providerType: text("provider_type"),
applicationKey: text("application_key"),
upstreamToolName: text("upstream_tool_name"),
riskLevel: text("risk_level").$type<ToolRiskLevel>(),
toolName: text("tool_name").notNull(),
argumentsHash: text("arguments_hash"),
argumentsSummary: jsonb("arguments_summary").$type<ToolRedactedValueSummary>(),
policyDecision: text("policy_decision").$type<ToolPolicyDecision>(),
matchedPolicyIds: jsonb("matched_policy_ids").$type<string[]>().notNull().default([]),
policyExplanation: jsonb("policy_explanation").$type<Record<string, unknown>>(),
credentialScopeSummary: jsonb("credential_scope_summary").$type<Record<string, unknown>>(),
headerPolicySummary: jsonb("header_policy_summary").$type<Record<string, unknown>>(),
approvalState: text("approval_state").$type<ToolInvocationApprovalState>().notNull().default("not_required"),
status: text("status").$type<ToolInvocationStatus>().notNull().default("pending"),
upstreamRequestId: text("upstream_request_id"),
resultHash: text("result_hash"),
resultSummary: jsonb("result_summary").$type<ToolRedactedValueSummary>(),
resultSizeBytes: integer("result_size_bytes"),
resultArtifactId: uuid("result_artifact_id"),
errorCode: text("error_code"),
errorMessage: text("error_message"),
startedAt: timestamp("started_at", { withTimezone: true }),
completedAt: timestamp("completed_at", { withTimezone: true }),
/** The provider's latest progress while the call runs (MCP `notifications/progress`), bounded. */
progress: jsonb("progress").$type<ToolCallProgress>(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_invocations_company_created_idx").on(table.companyId, table.createdAt),
index("tool_invocations_run_idx").on(table.companyId, table.runId),
index("tool_invocations_issue_idx").on(table.companyId, table.issueId),
index("tool_invocations_gateway_idx").on(table.companyId, table.gatewayId),
uniqueIndex("tool_invocations_company_idempotency_uq").on(table.companyId, table.idempotencyKey),
],
);
/**
* One completed call to a tool that declares an MCP Apps view. Holds what the
* task chat needs to render the view: the call's arguments and its redacted
* result. The view document itself is read from the connection on demand.
*/
export const toolMcpAppViews = pgTable(
"tool_mcp_app_views",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
invocationId: uuid("invocation_id").references(() => toolInvocations.id, { onDelete: "set null" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "cascade" }),
runId: uuid("run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }),
agentId: uuid("agent_id").references(() => agents.id, { onDelete: "set null" }),
responsibleUserId: text("responsible_user_id"),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
catalogEntryId: uuid("catalog_entry_id").references(() => toolCatalogEntries.id, { onDelete: "set null" }),
applicationName: text("application_name").notNull(),
toolName: text("tool_name").notNull(),
upstreamToolName: text("upstream_tool_name").notNull(),
resourceUri: text("resource_uri").notNull(),
toolInput: jsonb("tool_input").$type<Record<string, unknown>>().notNull().default({}),
toolResult: jsonb("tool_result").$type<Record<string, unknown>>().notNull(),
/** The view's latest `ui/update-model-context`, bounded. Delivered to the task's next run as untrusted app data. */
modelContext: jsonb("model_context").$type<McpAppModelContext>(),
modelContextUpdatedAt: timestamp("model_context_updated_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_mcp_app_views_issue_idx").on(table.companyId, table.issueId, table.createdAt),
index("tool_mcp_app_views_connection_idx").on(table.connectionId),
],
);
/**
* MCP Skills extension (`io.modelcontextprotocol/skills`): one row per skill a
* connected MCP server publishes. Identity is (connection, skill URI); the
* name is only a label. Approval binds to `manifestDigest`, the order-free
* digest of every `{uri, digest, size}` in the server's manifest, and any
* other manifest revokes it.
*/
export const toolMcpSkills = pgTable(
"tool_mcp_skills",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
skillUri: text("skill_uri").notNull(),
name: text("name").notNull(),
description: text("description").notNull().default(""),
/** The entry's frontmatter, verbatim. */
frontmatter: jsonb("frontmatter").$type<Record<string, unknown>>().notNull(),
/** `[{uri, digest, size}]` sorted by URI, or null for a dynamic skill. */
manifest: jsonb("manifest").$type<Array<{ uri: string; digest: string; size: number }> | null>(),
manifestDigest: text("manifest_digest"),
/** pending_review | approved | declined | unavailable */
status: text("status").notNull().default("pending_review"),
/** new | changed | dynamic | too_large | invalid | verification_failed | removed */
statusReason: text("status_reason"),
approvedManifestDigest: text("approved_manifest_digest"),
/** The skill's `allowed-tools`, honored only when approved with the skill. */
allowedToolsApproved: boolean("allowed_tools_approved").notNull().default(false),
reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
reviewedByUserId: text("reviewed_by_user_id"),
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("tool_mcp_skills_connection_uri_idx").on(table.companyId, table.connectionId, table.skillUri),
index("tool_mcp_skills_company_status_idx").on(table.companyId, table.status),
],
);
/**
* A provider task (MCP Tasks extension) that a `tools/call` returned in place
* of its result. The row is the durable handle: polling resumes from it after
* a restart, and a repeated call with the same request identity, grant, and
* agent attaches to it instead of starting the work again. No provider result
* is stored here; the result is read from the provider when it is delivered.
*/
export const toolMcpTasks = pgTable(
"tool_mcp_tasks",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
/** The call that created the task. */
invocationId: uuid("invocation_id").notNull().references(() => toolInvocations.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
/** The grant whose credentials created the task; only that grant may read it. */
grantId: uuid("grant_id").notNull(),
agentId: uuid("agent_id"),
issueId: uuid("issue_id"),
/** The latest run that waited on the task. */
runId: uuid("run_id"),
actorType: text("actor_type").notNull(),
actorId: text("actor_id"),
/** The person whose grant applied, and the run identity, so background checks see the same caller. */
responsibleUserId: text("responsible_user_id"),
identityContextId: uuid("identity_context_id"),
catalogToolName: text("catalog_tool_name").notNull(),
/** Endpoint, tool, and full arguments; a call attaches only on an exact match. */
requestHash: text("request_hash").notNull(),
endpointHash: text("endpoint_hash").notNull(),
/** Forwarded caller headers the connection allows (such as a tenant), sealed; background polls send them too. */
sealedCallerHeaders: text("sealed_caller_headers"),
protocolVersion: text("protocol_version").notNull(),
/** The provider's task ID, sealed: it may act as a bearer token. */
sealedProviderTaskId: text("sealed_provider_task_id").notNull(),
/** Keyed hash of the provider's task ID, for uniqueness without the ID. */
providerTaskIdHash: text("provider_task_id_hash").notNull(),
/** working | input_required | completed | failed | cancelled | expired */
status: text("status").notNull(),
pollIntervalMs: integer("poll_interval_ms"),
ttlMs: integer("ttl_ms"),
/** When Paperclip stops tracking the task (the provider's TTL, capped). */
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
/** Next background check; null when nothing is left to do. */
nextPollAt: timestamp("next_poll_at", { withTimezone: true }),
lastPolledAt: timestamp("last_polled_at", { withTimezone: true }),
pollFailures: integer("poll_failures").notNull().default(0),
/** A live call or the background worker holds the task until then. */
leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
/** Who holds the lease; writes under a lease require it. */
leaseOwner: text("lease_owner"),
/** The gateway's keyed identity of the full arguments, for keyed retries. */
argumentsIdentity: text("arguments_identity").notNull(),
/** Input request keys already answered with `tasks/update`. */
answeredInputKeys: jsonb("answered_input_keys").$type<string[]>().notNull().default([]),
/** Input request keys already shown to the agent (a link or a question card). */
surfacedInputKeys: jsonb("surfaced_input_keys").$type<string[]>().notNull().default([]),
/** Wakes requested for new input requests; capped, so a provider cannot wake an agent without end. */
inputWakeCount: integer("input_wake_count").notNull().default(0),
inputWakeAt: timestamp("input_wake_at", { withTimezone: true }),
errorCode: text("error_code"),
wakeRequestedAt: timestamp("wake_requested_at", { withTimezone: true }),
deliveredAt: timestamp("delivered_at", { withTimezone: true }),
/** The latest call that waited on the task (a retry with its key attaches again). */
lastInvocationId: uuid("last_invocation_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("tool_mcp_tasks_provider_task_uq").on(table.companyId, table.connectionId, table.providerTaskIdHash),
index("tool_mcp_tasks_attach_idx").on(table.companyId, table.connectionId, table.requestHash),
index("tool_mcp_tasks_invocation_idx").on(table.companyId, table.invocationId),
index("tool_mcp_tasks_next_poll_idx").on(table.nextPollAt).where(sql`${table.nextPollAt} is not null`),
],
);
/**
* A provider's form question waiting on a person (MCP elicitation). One row per
* question round: a stateless server's `input_required` result, or one older
* server's `elicitation/create`. The question cards hold the answers; this row
* holds what the repeated call needs to send them back, exactly once.
*/
export const toolMcpElicitations = pgTable(
"tool_mcp_elicitations",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
issueId: uuid("issue_id").notNull(),
agentId: uuid("agent_id"),
runId: uuid("run_id"),
/** The call that was asked. */
invocationId: uuid("invocation_id").notNull().references(() => toolInvocations.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
/** Only the same grant's repeated call may send the answers. */
grantId: uuid("grant_id").notNull(),
catalogToolName: text("catalog_tool_name").notNull(),
/** Keyed identity of endpoint, tool, arguments, grant, and agent; only an identical call collects the round. */
callIdentity: text("call_identity").notNull(),
/** modern: a stateless input_required round. legacy: one server-initiated question. */
era: text("era").notNull(),
/** The server's opaque requestState, sealed (it may carry authority). */
sealedRequestState: text("sealed_request_state"),
/** One entry per form question: the server's key, its words and schema (shown on the card, never an answer), and its card. */
questions: jsonb("questions").$type<Array<{
key: string; questionHash: string;
/** The card's idempotency key: the round is saved before its cards, and a missing card is made again. */
cardKey: string;
interactionId?: string;
message: string; requestedSchema: Record<string, unknown> | null;
}>>().notNull(),
/** Keyed identity of the tool name and full arguments; a keyed retry runs again only for the same request. */
argumentsIdentity: text("arguments_identity").notNull(),
/** One waiting round per call (and per question, for older servers): matching calls at once share its cards. */
dedupeKey: text("dedupe_key").notNull(),
/** waiting | sent | expired */
status: text("status").notNull(),
/** A repeated call sending the answers holds the round until then. */
claimedUntil: timestamp("claimed_until", { withTimezone: true }),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
sentAt: timestamp("sent_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_mcp_elicitations_call_idx").on(table.companyId, table.issueId, table.connectionId, table.callIdentity, table.status),
index("tool_mcp_elicitations_invocation_idx").on(table.companyId, table.invocationId),
uniqueIndex("tool_mcp_elicitations_waiting_uq").on(table.companyId, table.issueId, table.dedupeKey)
.where(sql`${table.status} = 'waiting'`),
],
);
/**
* Verified skill files, written only by the server after a size and SHA-256
* check and never changed in place. Rows are keyed by connection and digest,
* so the same URI from two servers never shares bytes. Agents cannot write
* here and nothing scans it for skills.
*/
export const toolMcpSkillFiles = pgTable(
"tool_mcp_skill_files",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
fileUri: text("file_uri").notNull(),
digest: text("digest").notNull(),
size: integer("size").notNull(),
contentBase64: text("content_base64").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("tool_mcp_skill_files_digest_idx").on(table.companyId, table.connectionId, table.fileUri, table.digest),
],
);
export const toolActionRequests = pgTable(
"tool_action_requests",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
invocationId: uuid("invocation_id").notNull().references(() => toolInvocations.id, { onDelete: "cascade" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
interactionId: uuid("interaction_id").references(() => issueThreadInteractions.id, { onDelete: "set null" }),
approvalId: uuid("approval_id").references(() => approvals.id, { onDelete: "set null" }),
status: text("status").$type<ToolActionRequestStatus>().notNull().default("pending"),
canonicalArgumentsHash: text("canonical_arguments_hash").notNull(),
canonicalArgumentsSummary: jsonb("canonical_arguments_summary").$type<ToolRedactedValueSummary>().notNull(),
signedArguments: text("signed_arguments"),
previewMarkdown: text("preview_markdown"),
requestedByAgentId: uuid("requested_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
requestedByUserId: text("requested_by_user_id"),
resolvedByAgentId: uuid("resolved_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
resolvedByUserId: text("resolved_by_user_id"),
decidedByAgentId: uuid("decided_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
decidedByUserId: text("decided_by_user_id"),
decidedAt: timestamp("decided_at", { withTimezone: true }),
expiresAt: timestamp("expires_at", { withTimezone: true }),
resolvedAt: timestamp("resolved_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_action_requests_company_status_idx").on(table.companyId, table.status),
index("tool_action_requests_pending_expiry_idx").on(table.expiresAt, table.id)
.where(sql`${table.status} = 'pending'`),
index("tool_action_requests_company_pending_expiry_idx").on(table.companyId, table.expiresAt)
.where(sql`${table.status} = 'pending'`),
index("tool_action_requests_executing_deadline_idx").on(table.updatedAt, table.id).where(sql`${table.status} = 'executing'`),
index("tool_action_requests_approved_idx").on(table.id).where(sql`${table.status} = 'approved'`),
index("tool_action_requests_invocation_idx").on(table.invocationId),
index("tool_action_requests_company_interaction_idx").on(table.companyId, table.interactionId),
index("tool_action_requests_issue_idx").on(table.companyId, table.issueId),
],
);
export const toolCallEvents = pgTable(
"tool_call_events",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
eventType: text("event_type").$type<ToolAuditEventType>().notNull(),
actorType: text("actor_type").notNull().default("system"),
actorId: text("actor_id"),
agentId: uuid("agent_id").references(() => agents.id, { onDelete: "set null" }),
runId: uuid("run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
gatewayId: uuid("gateway_id").references(() => toolMcpGateways.id, { onDelete: "set null" }),
gatewayTokenId: uuid("gateway_token_id").references(() => toolMcpGatewayTokens.id, { onDelete: "set null" }),
gatewayPublicId: text("gateway_public_id"),
clientSubjectType: text("client_subject_type").$type<ToolMcpGatewayTokenSubjectType>(),
clientSubjectId: text("client_subject_id"),
clientName: text("client_name"),
mcpSessionId: text("mcp_session_id"),
correlationId: text("correlation_id"),
applicationId: uuid("application_id").references(() => toolApplications.id, { onDelete: "set null" }),
connectionId: uuid("connection_id").references(() => toolConnections.id, { onDelete: "set null" }),
catalogEntryId: uuid("catalog_entry_id").references(() => toolCatalogEntries.id, { onDelete: "set null" }),
invocationId: uuid("invocation_id").references(() => toolInvocations.id, { onDelete: "set null" }),
actionRequestId: uuid("action_request_id").references(() => toolActionRequests.id, { onDelete: "set null" }),
runtimeSlotId: uuid("runtime_slot_id").references(() => toolRuntimeSlots.id, { onDelete: "set null" }),
toolName: text("tool_name"),
decision: text("decision").$type<ToolPolicyDecision>(),
matchedPolicyIds: jsonb("matched_policy_ids").$type<string[]>().notNull().default([]),
reasonCode: text("reason_code"),
policyExplanation: jsonb("policy_explanation").$type<Record<string, unknown>>(),
credentialScopeSummary: jsonb("credential_scope_summary").$type<Record<string, unknown>>(),
headerPolicySummary: jsonb("header_policy_summary").$type<Record<string, unknown>>(),
outcome: text("outcome").$type<ToolAuditOutcome>().notNull().default("pending"),
latencyMs: integer("latency_ms"),
argumentsSummary: jsonb("arguments_summary").$type<ToolRedactedValueSummary>(),
requestHash: text("request_hash"),
requestSummary: jsonb("request_summary").$type<ToolRedactedValueSummary>(),
resultHash: text("result_hash"),
resultSummary: jsonb("result_summary").$type<ToolRedactedValueSummary>(),
resultSizeBytes: integer("result_size_bytes"),
redactionPlan: jsonb("redaction_plan").$type<Record<string, unknown>>(),
rateLimitState: jsonb("rate_limit_state").$type<Record<string, unknown>>(),
metadata: jsonb("metadata").$type<Record<string, unknown>>(),
errorCode: text("error_code"),
errorMessage: text("error_message"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_call_events_company_created_idx").on(table.companyId, table.createdAt),
index("tool_call_events_run_idx").on(table.companyId, table.runId),
index("tool_call_events_issue_idx").on(table.companyId, table.issueId),
index("tool_call_events_invocation_idx").on(table.invocationId),
index("tool_call_events_gateway_idx").on(table.companyId, table.gatewayId),
],
);
export const connectionTokenIssuances = pgTable(
"connection_token_issuances",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
applicationId: uuid("application_id").references(() => toolApplications.id, { onDelete: "set null" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }),
runId: uuid("run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }),
projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }),
responsibleUserId: text("responsible_user_id"),
path: text("path").$type<ConnectionTokenIssuancePath>().notNull(),
requestedScope: jsonb("requested_scope").$type<string[]>().notNull().default([]),
issuedScope: jsonb("issued_scope").$type<string[]>().notNull().default([]),
ttlSeconds: integer("ttl_seconds"),
expiresAt: timestamp("expires_at", { withTimezone: true }),
tokenHash: text("token_hash"),
outcome: text("outcome").$type<ConnectionTokenIssuanceOutcome>().notNull(),
errorCode: text("error_code"),
metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("connection_token_issuances_company_created_idx").on(table.companyId, table.createdAt),
index("connection_token_issuances_connection_created_idx").on(table.companyId, table.connectionId, table.createdAt),
index("connection_token_issuances_agent_connection_idx").on(table.companyId, table.agentId, table.connectionId, table.createdAt),
index("connection_token_issuances_run_idx").on(table.companyId, table.runId),
sql`CONSTRAINT connection_token_issuances_path_check CHECK (${table.path} IN ('exchange', 'oauth_access', 'static'))`,
sql`CONSTRAINT connection_token_issuances_outcome_check CHECK (${table.outcome} IN ('success', 'denied', 'rate_limited', 'use_env_lease', 'upstream_error', 'failure'))`,
sql`CONSTRAINT connection_token_issuances_ttl_bounds CHECK (${table.ttlSeconds} IS NULL OR (${table.ttlSeconds} >= 1 AND ${table.ttlSeconds} <= 900))`,
sql`CONSTRAINT connection_token_issuances_token_hash_format CHECK (${table.tokenHash} IS NULL OR ${table.tokenHash} ~ '^[a-f0-9]{64}$')`,
],
);
export const toolRateLimitCounters = pgTable(
"tool_rate_limit_counters",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
policyId: uuid("policy_id").notNull().references(() => toolPolicies.id, { onDelete: "cascade" }),
counterKey: text("counter_key").notNull(),
scopeType: text("scope_type").notNull(),
scopeId: text("scope_id").notNull(),
windowKind: text("window_kind").$type<ToolRateLimitWindowKind>().notNull(),
windowStartAt: timestamp("window_start_at", { withTimezone: true }).notNull(),
limit: integer("limit").notNull(),
remaining: integer("remaining").notNull(),
resetAt: timestamp("reset_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_rate_limit_counters_company_idx").on(table.companyId),
uniqueIndex("tool_rate_limit_counters_window_uq").on(
table.companyId,
table.policyId,
table.counterKey,
table.windowKind,
table.windowStartAt,
),
],
);
export const toolRuntimeMetricCounters = pgTable(
"tool_runtime_metric_counters",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
metric: text("metric").notNull(),
bucketStartAt: timestamp("bucket_start_at", { withTimezone: true }).notNull(),
count: integer("count").notNull().default(0),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_runtime_metric_counters_company_metric_idx").on(table.companyId, table.metric, table.bucketStartAt),
uniqueIndex("tool_runtime_metric_counters_bucket_uq").on(table.companyId, table.metric, table.bucketStartAt),
sql`CONSTRAINT tool_runtime_metric_counters_count_nonnegative CHECK (${table.count} >= 0)`,
],
);
export const toolAccessAuditEvents = pgTable(
"tool_access_audit_events",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
gatewayId: uuid("gateway_id").references(() => toolMcpGateways.id, { onDelete: "set null" }),
gatewayTokenId: uuid("gateway_token_id").references(() => toolMcpGatewayTokens.id, { onDelete: "set null" }),
gatewayPublicId: text("gateway_public_id"),
clientName: text("client_name"),
correlationId: text("correlation_id"),
connectionId: uuid("connection_id").references(() => toolConnections.id, { onDelete: "set null" }),
catalogEntryId: uuid("catalog_entry_id").references(() => toolCatalogEntries.id, { onDelete: "set null" }),
actorType: text("actor_type").notNull().default("system"),
actorId: text("actor_id"),
action: text("action").notNull(),
outcome: text("outcome").notNull(),
reasonCode: text("reason_code"),
details: jsonb("details").$type<Record<string, unknown>>().notNull().default({}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("tool_access_audit_company_created_idx").on(table.companyId, table.createdAt),
index("tool_access_audit_connection_idx").on(table.connectionId),
index("tool_access_audit_gateway_idx").on(table.companyId, table.gatewayId),
],
);