Files
shumai/packages/db/prisma/schema.prisma
T
Yiling-J 1b5cbf936a feat(mcp): add MCP server support with proxy tool and OAuth flow (#289)
* feat(mcp): add MCP server support with proxy tool and OAuth flow

Add URL-based MCP (Model Context Protocol) server support to the backend:

- DB: McpServer / AgentMcpServer / McpServerCredential models with
  typed JSON columns (auth config, cached tools, stored OAuth tokens,
  pending auth state) and a migration.
- Core (@shumai/core/src/mcp): DB-backed credential store, OAuth
  client provider (authorization_code + client_credentials) with a
  Hono-hosted redirect callback, connection lifecycle manager
  (Streamable HTTP with SSE fallback, lazy connect, 401 -> needs_auth),
  JSON Schema -> AgentTool parameter conversion, in-memory tool registry
  with ranked search, the single 'mcp' proxy AgentTool (search /
  describe / list / call / connect / status / auth-start), per-server
  opt-in direct tools ({server}_{tool}), and McpService (CRUD,
  discovery, OAuth, per-agent assignment via AgentMcpServer, and
  permission gating on tool execution mirroring skills).
- Agent: chat agents receive the 'mcp' proxy tool (plus direct tools
  for opted-in servers) built from their assigned, enabled servers.
- API: /teams/:teamId/mcp/servers CRUD, tools refresh/list, auth
  start/complete/status/remove, test, permission, and the public
  OAuth callback route; Admin authz via new ResourceType.McpServer;
  audit logging.
- DTOs: zod schemas + types for servers, tools, auth, and per-agent
  mcpServerIds.
- Tests: DB store, schema conversion, registry/search, service
  integration against a real in-process MCP server (v2
  @modelcontextprotocol/server), permission gating, rename
  invalidation, direct tools, per-agent assignment, API route tests,
  and workflow E2E (local + temporal) for proxy and direct modes.

* fix(mcp): persist OAuth discovery snapshot and stamp SEP-2352 issuer

The callback leg of the OAuth flow failed with
AuthorizationServerMismatchError ('discoveryState was not available on
the callback leg') because McpDbStore.savePendingAuth overwrote the
entire pendingAuth JSON column, clobbering the discoverySnapshot that
the provider's saveDiscoveryState() had stored inside it.

- McpDbStore.savePendingAuth now preserves an in-flight discovery
  snapshot so the callback leg can satisfy the SEP-2352 authorization-
  server issuer check.
- McpOauthProvider now round-trips the issuer stamp derived from the
  discovery snapshot: saveClientInformation/saveTokens persist it,
  clientInformation()/tokens() return it, and tokens() backfills a
  missing stamp for pre-existing credentials (removes the
  'stored OAuth credential has no issuer stamp' warning).
- Regression tests: savePendingAuth keeps the snapshot; the provider
  stamps/round-trips the issuer on both legs.

* fix(mcp): backfill SEP-2352 issuer stamp on stale OAuth client info

clientInformation() returned stored client info without an issuer field
when it had been dynamically registered before the stamping fix, so the
SDK logged 'stored OAuth credential has no issuer stamp' on every read.
Now the stored branch backfills the issuer from the discovery snapshot
(persisting it) exactly like the tokens() backfill.

* feat(webui): add MCP server configuration and agent assignment UI (#290)

* feat(webui): add MCP server configuration and agent assignment UI

* fix(webui): auto-detect auth for unconfigured MCP servers and show connect button

* fix(mcp): auto-generate state in mcp-oauth-provider when missing in DB

* fix(mcp): persist OAuth discovery snapshot and stamp SEP-2352 issuer

The callback leg of the OAuth flow failed with
AuthorizationServerMismatchError ('discoveryState was not available on
the callback leg') because McpDbStore.savePendingAuth overwrote the
entire pendingAuth JSON column, clobbering the discoverySnapshot that
the provider's saveDiscoveryState() had stored inside it.

- McpDbStore.savePendingAuth now preserves an in-flight discovery
  snapshot so the callback leg can satisfy the SEP-2352 authorization-
  server issuer check.
- McpOauthProvider now round-trips the issuer stamp derived from the
  discovery snapshot: saveClientInformation/saveTokens persist it,
  clientInformation()/tokens() return it, and tokens() backfills a
  missing stamp for pre-existing credentials (removes the
  'stored OAuth credential has no issuer stamp' warning).
- Regression tests: savePendingAuth keeps the snapshot; the provider
  stamps/round-trips the issuer on both legs.

* fix(mcp): backfill SEP-2352 issuer stamp on stale OAuth client info

clientInformation() returned stored client info without an issuer field
when it had been dynamically registered before the stamping fix, so the
SDK logged 'stored OAuth credential has no issuer stamp' on every read.
Now the stored branch backfills the issuer from the discovery snapshot
(persisting it) exactly like the tokens() backfill.

* fix(mcp): attach McpOauthProvider for auto-detected OAuth servers and discover tools on auth completion

* fix(webui): fix flex min-h-0 and max-h scrolling on MCP tools dialog

* fix(webui): set explicit flex height on McpToolsDialog for active scrolling

* feat(webui): make MCP server cards clickable to edit and widen server config dialog

* feat(mcp): agent-level server enablement and auto-detected server metadata (#291)

* feat(mcp): agent-level server enablement and auto-detected server metadata

- Remove the server-level `enabled` column from mcp_servers; enable/disable
  now happens per-agent via the AgentMcpServer join table (mirrors skills).
- Drop the unique (teamId, name) constraint so duplicate server names are allowed.
- Add a `description` column, auto-filled from client.getServerVersion() on
  connect; the server name is auto-filled from the reported title (fallback name)
  with a URL-derived placeholder until first connect.
- Remove manual name input: the create dialog is URL-only, and the edit dialog
  shows the auto-detected name/description read-only.
- Replace the include/exclude raw-text inputs with the tool list in the edit
  dialog, managing only excludeTools; remove includeTools support and the
  separate McpToolsDialog component.
- Sanitize server-reported names into safe direct-tool prefixes (spaces/punctuation
  become underscores) and use the same sanitization in the proxy resolver.

* fix(mcp): give the edit-dialog tool list a definite height

The Shadcn ScrollArea viewport is h-full, which requires a definite height
on the root. Using max-h-64 left the viewport at auto height, so the root
clipped the list at 256px without engaging its own scrollbar — tools past
the cutoff were unreachable. Use a fixed h-64 container (same pattern as
move-copy-dialog) so the inner scroll area scrolls independently of the
dialog's outer scroll.

* refactor(mcp): fixed header/footer with scrollable content in server config dialog

Mirror the skill config dialog layout: the edit dialog now keeps the header
and footer fixed and scrolls only the content area (ScrollArea flex-1
min-h-0 inside an h-[85vh] flex column). The tools list no longer has its
own nested ScrollArea — it flows inside the content-level scroll, so all
tools are reachable without a nested-scroll conflict. The create dialog
stays compact (URL-only) like the skill add dialog.

Verified headlessly that max-height-based ScrollArea roots do not engage
scrolling (viewport height resolves to auto), which is why the previous
nested list clipped; the flex-based definite-height pattern scrolls.

* feat(mcp): make the endpoint URL immutable after creation

Editing a server's URL effectively points it at a different server, and the
create flow is URL-only anyway — so the edit dialog no longer allows changing
it (delete + re-add covers endpoint changes). The URL is displayed read-only
next to the auto-detected name/description, and `url` was removed from the
update DTO and service; auth/transport changes still invalidate credentials
and cached tools.

* refactor(mcp): match MCP server cards to the skill card layout

The settings list cards now share the skill card structure: row 1 is the
server name (with direct-mode/transport badges) plus the three-dot menu,
row 2 is the description (falling back to 'No description provided') with
the endpoint URL and last error as small mono lines, and row 3 holds the
connection-status badge and updated date on the left with the permission
selector and the connect button at the right end.

* fix(mcp): stop card menu clicks from opening the edit dialog

The three-dot menu is portaled, so its item clicks bubble through React's
synthetic events to the card's onClick, which opened the edit dialog before
the delete confirmation appeared. Add e.stopPropagation() to every menu
item (matching the skill card pattern).

* fix(mcp): stop Refresh Tools from submitting/closing the config dialog

The Refresh Tools button lived inside the <form> and, like all buttons
without an explicit type, defaulted to type="submit" — clicking it ran the
form submit (save + close) instead of just refreshing. Set type="button".

Also per UX: while refreshing, the button is disabled with a spinning icon,
the per-tool enable/disable switches are disabled, and the success toast is
removed — the button reverting to its idle state is the success signal
(keep the error toast for failures).

* test(mcp): provide explicit redirectUri in McpOauthProvider test helper

* fix(mcp): scope tool registry to agent-assigned servers

The MCP tool registry was a process-global singleton keyed by server id,
so a chat agent could search, describe, and even call tools belonging to
MCP servers that were not assigned to it (e.g. disabled or unassigned
servers), as long as their metadata had been discovered at some point in
the process. This mirrors the disabled-skill bug: the read path never
checked per-agent enablement.

Replace the singleton with a fresh McpToolRegistry built per
buildAgentTools call and warmed from the persisted McpServer.tools DB
cache. Because the registry only ever contains the agent's assigned
servers, unassigned/disabled servers can neither be suggested, searched,
described, nor executed. Live discovery (lazy connect / connect action)
writes into the per-agent registry via ensureConnected(serverId,
registry?).

Adds test-first coverage: suggestions, search, describe and tool-call
leaks across an unassigned same-team server, staleness after
unassignment, and direct-tools scoping.

* feat(mcp): capture and surface server instructions + server-level refresh (#293)

* feat(mcp): capture and surface server instructions

- Add McpServer.instructions column, populated from getInstructions() at
  connect time (legacy initialize + modern discover results)
- Surface instructions at three levels like pi-mcp-adapter: truncated
  snippet in the mcp proxy tool description, preview in server listings,
  and full text via mcp({ instructions: "name" })
- Fix misleading mcp({ server, connect }) usage line to mcp({ connect })
- Share one renderServerListing helper across list and connect modes
- Expose instructions in McpServerInfo DTO and WebUI config card
- Test server supports instructions; service + API tests updated

* refactor(mcp): server-level refresh endpoint, drop agent connect mode

- Replace POST /mcp/servers/:id/tools/refresh with POST /mcp/servers/:id/refresh
  returning the refreshed McpServerInfo (server-level, not tools-level)
- Add McpService.refreshServer(): force-close the connection, re-discover and
  persist tools, instructions, name/description and status; used by the refresh
  endpoint, Test Connection, and post-OAuth completion (replacing discoverTools)
- Remove discoverTools entirely - refreshServer is the single discovery entry
  point (testServer and completeAuth route through it)
- Remove refreshTools from UpdateMcpServerRequest/PATCH (dead param)
- Remove mcp({ connect: "name" }) from the agent proxy tool: lazy tool calls
  still auto-connect, so agents are unaffected
- WebUI: remove the dialog 'Refresh Tools' button and create-mode background
  auto-refresh; add a server-level Refresh button at the left end of the edit
  dialog footer; i18n mcp_refresh_server (+ success message)

* feat(mcp): add in-flight request tracking and idle connection cleanup (#294)

* feat(mcp): add in-flight request tracking and idle connection cleanup

* feat(mcp): add background idle cleanup timer to McpService

* feat(mcp): update default background idle cleanup check interval to 30s

* feat(webui): improve MCP server card footer, instructions, and refresh dialog freeze (#295)

* feat(webui): improve MCP server list card, instructions dialog, and refresh freeze UI

* feat(webui): refine MCP card action menu items

* docs(webui): update direct tools mode description in i18n messages

* style(webui): refine Direct Tools Mode layout in MCP server config dialog

* feat(webui): remove tool search box from MCP server config dialog

* fix(mcp): make in-flight idle tracking test deterministic

The 'tracks in-flight requests and safely prunes idle connections' test
relied on a wall-clock sleep (10ms) to guess when the tool handler had
started executing on the server. On slow/loaded CI runners the HTTP round
trip through the real MCP client/server stack can exceed that window, so
resolveSlowTool() fired the no-op placeholder, the gated handler never
completed, and callPromise hung until the 5000ms test timeout.

The handler now signals via a deferred promise when it actually starts,
and the test awaits that signal (racing it against the call promise to
surface early failures) before asserting in-flight state and releasing
the gate. Also gives the test an explicit 10s timeout.
2026-08-11 11:01:38 +08:00

1010 lines
34 KiB
Plaintext

generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
previewFeatures = ["postgresqlExtensions"]
}
generator json {
provider = "prisma-json-types-generator"
allowAny = false
}
datasource db {
provider = "postgresql"
extensions = [vector]
}
// ----------------------------------------------------------------------
// Enums
// ----------------------------------------------------------------------
enum UserType {
human
agent
}
enum AssetType {
folder
file
share
root
attachment
version_stack
share_root
symlink
}
enum AssetStatus {
uploading
uploaded
processing
processed
trashed
pending_purge
}
enum StorageKeyStatus {
active
purging
}
enum InviteRole {
editor
reviewer
}
enum MetadataFieldScope {
SYSTEM
TEAM
PROJECT
}
enum NotificationType {
comment_created
reply_created
mention
successful_file_uploaded
metadata_field_updated_status
new_user_join_team
new_user_join_project
}
enum ProjectMemberRole {
owner
editor
reviewer
}
enum TaskType {
upload
}
enum TaskStatus {
pending
uploading
completed
failed
}
enum TeamMemberRole {
owner
editor
reviewer
}
enum TeamMemberScope {
team
project
}
enum WorkflowTaskType {
transcode
transcode_video
transcode_image
transcode_pdf
transcode_pdf_pages
transcode_screenshot
transcode_image_annotation
transcode_watermark
ai_metadata_autofill
chat
ai_embedding
query_embedding_for_search
agent_tool_call
}
enum WorkflowTaskStatus {
pending
processing
completed
failed
}
enum WatermarkStatus {
disabled
processing
ready
failed
}
enum WatermarkFileStatus {
pending
processing
completed
failed
}
// ----------------------------------------------------------------------
// Models
// ----------------------------------------------------------------------
model User {
id String @id @default(ulid())
type UserType @default(human)
name String
email String @unique
emailVerified Boolean @default(false) @map("email_verified")
image String?
password String?
/// [AgentSettings]
agentSettings Json? @map("agent_settings")
guestEmail String? @map("guest_email")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assets Asset[] @relation("UserToAsset")
authTokens AuthToken[] @relation("UserToAuthToken")
tasks Task[] @relation("UserToTask")
teamMembers TeamMember[] @relation("UserToTeamMember")
comments AssetComment[] @relation("UserToAssetComment")
completionChangedComments AssetComment[] @relation("UserToAssetCommentCompletionChanged")
createdInvites Invite[] @relation("UserToInvite")
createdNotifications Notification[] @relation("UserToCreatedNotification")
notifications Notification[] @relation("UserToNotification")
sessions Session[]
accounts Account[]
agent Agent?
agentSessions AgentSession[]
userMetadata UserMetadata[] @relation("UserToUserMetadata")
collections Collection[] @relation("UserToCollection")
shareLinks ShareLink[] @relation("UserToShareLink")
apiTokens ApiToken[] @relation("UserToApiToken")
aiUsages AiUsage[] @relation("UserToAiUsage")
auditLogs AuditLog[] @relation("UserToAuditLog")
@@map("users")
}
model Session {
id String @id @default(ulid())
expiresAt DateTime @map("expires_at")
token String @unique
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
ipAddress String? @map("ip_address")
userAgent String? @map("user_agent")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("sessions")
}
model Account {
id String @id @default(ulid())
accountId String @map("account_id")
providerId String @map("provider_id")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String? @map("access_token")
refreshToken String? @map("refresh_token")
idToken String? @map("id_token")
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
scope String?
password String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("accounts")
}
model Verification {
id String @id @default(ulid())
identifier String
value String
expiresAt DateTime @map("expires_at")
createdAt DateTime? @default(now()) @map("created_at")
updatedAt DateTime? @updatedAt @map("updated_at")
@@map("verifications")
}
model AuthToken {
id String @id @default(ulid())
accessToken String @unique @map("access_token")
refreshToken String @unique @map("refresh_token")
accessTokenExpiresAt DateTime @map("access_token_expires_at")
refreshTokenExpiresAt DateTime @map("refresh_token_expires_at")
userId String @map("user_id")
user User @relation("UserToAuthToken", fields: [userId], references: [id])
@@map("auth_tokens")
}
model Team {
id String @id @default(ulid())
name String
/// [Settings]
settings Json? @default("{}")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
rootFolderId String? @unique @map("root_folder_id")
rootFolder Asset? @relation("TeamToRootFolder", fields: [rootFolderId], references: [id])
members TeamMember[] @relation("TeamToTeamMember")
projects Project[] @relation("TeamToProject")
metadataFields MetadataField[] @relation("TeamToMetadataField")
invites Invite[] @relation("TeamToInvite")
notifications Notification[] @relation("TeamToNotification")
userMetadata UserMetadata[] @relation("TeamToUserMetadata")
providers Provider[] @relation("TeamToProvider")
skills Skill[] @relation("TeamToSkill")
mcpServers McpServer[] @relation("TeamToMcpServer")
sandbox Sandbox? @relation("TeamToSandbox")
agents Agent[] @relation("TeamToAgent")
aiUsages AiUsage[] @relation("TeamToAiUsage")
auditLogs AuditLog[] @relation("TeamToAuditLog")
watermarkTemplates WatermarkTemplate[] @relation("TeamToWatermarkTemplate")
@@map("teams")
}
model Sandbox {
id String @id @default(ulid())
allowedDomains String[] @default(["npmjs.org", "*.npmjs.org", "registry.npmjs.org", "registry.yarnpkg.com", "pypi.org", "*.pypi.org", "github.com", "*.github.com", "api.github.com", "raw.githubusercontent.com"])
pendingDomains String[] @default([]) @map("pending_domains")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @unique @map("team_id")
team Team @relation("TeamToSandbox", fields: [teamId], references: [id], onDelete: Cascade)
@@map("sandboxes")
}
model Skill {
id String @id @default(ulid())
name String
description String?
/// [SkillConfig]
config Json? @default("{}")
assetId String @map("asset_id")
hash String @map("hash")
permission TeamMemberRole @default(reviewer)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToSkill", fields: [teamId], references: [id], onDelete: Cascade)
agentSkills AgentSkill[]
@@unique([teamId, name])
@@map("skills")
}
model TeamMember {
id String @id @default(ulid())
role TeamMemberRole
scope TeamMemberScope @default(team)
teamId String @map("team_id")
team Team @relation("TeamToTeamMember", fields: [teamId], references: [id])
userId String @map("user_id")
user User @relation("UserToTeamMember", fields: [userId], references: [id], onDelete: Cascade)
projectMembers ProjectMember[] @relation("TeamMemberToProjectMember")
lastReadNotificationId String? @unique @map("last_read_notification_id")
lastReadNotification Notification? @relation("TeamMemberToLastReadNotification", fields: [lastReadNotificationId], references: [id])
@@map("team_members")
@@unique([teamId, userId], name: "teamIdUserId")
}
model Project {
id String @id @default(ulid())
name String
coverImageKey String? @map("cover_image_key")
/// [MetadataOverrides]
metadataOverrides Json? @map("metadata_overrides")
enableNotification Boolean @default(true) @map("enable_notification")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToProject", fields: [teamId], references: [id])
rootFolderId String? @unique @map("root_folder_id")
rootFolder Asset? @relation("ProjectToRootFolder", fields: [rootFolderId], references: [id])
shareRootId String? @unique @map("share_root_id")
shareRoot Asset? @relation("ProjectToShareRoot", fields: [shareRootId], references: [id])
members ProjectMember[] @relation("ProjectToProjectMember")
assets Asset[] @relation("ProjectToAsset")
metadataFields MetadataField[] @relation("ProjectToMetadataField")
invites Invite[] @relation("ProjectToInvite")
notifications Notification[] @relation("ProjectToNotification")
shareLinks ShareLink[] @relation("ProjectToShareLink")
collections Collection[] @relation("ProjectToCollection")
auditLogs AuditLog[] @relation("ProjectToAuditLog")
@@map("projects")
@@index([createdAt])
@@index([updatedAt])
}
model ProjectMember {
id String @id @default(ulid())
role ProjectMemberRole
projectId String @map("project_id")
project Project @relation("ProjectToProjectMember", fields: [projectId], references: [id], onDelete: Cascade)
teamMemberId String @map("team_member_id")
teamMember TeamMember @relation("TeamMemberToProjectMember", fields: [teamMemberId], references: [id])
@@map("project_members")
@@unique([projectId, teamMemberId], name: "projectIdTeamMemberId")
}
model ShareLink {
id String @id @default(ulid())
name String
expireAt DateTime? @map("expire_at")
password String?
isDisabled Boolean @default(false) @map("is_disabled")
allowDownload Boolean @default(true) @map("allow_download")
defaultSortOrder String? @map("default_sort_order")
viewMode String? @map("view_mode")
/// [ShareLinkFieldVisibility]
fieldVisibility Json? @map("field_visibility")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation("ProjectToShareLink", fields: [projectId], references: [id], onDelete: Cascade)
rootFolderId String @unique @map("root_folder_id")
rootFolder Asset @relation("ShareLinkToRootFolder", fields: [rootFolderId], references: [id])
creatorId String? @map("creator_id")
creator User? @relation("UserToShareLink", fields: [creatorId], references: [id])
watermarkConfigId String? @map("watermark_config_id")
watermarkStatus WatermarkStatus @default(disabled) @map("watermark_status")
watermarkConfig WatermarkConfig? @relation(fields: [watermarkConfigId], references: [id], onDelete: SetNull)
@@map("share_links")
}
model WatermarkConfig {
id String @id @default(ulid())
/// [WatermarkConfigSpec]
config Json
hash String @unique
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
shareLinks ShareLink[]
watermarkFiles WatermarkFile[]
@@map("watermark_configs")
}
model WatermarkTemplate {
id String @id @default(ulid())
name String
/// [WatermarkConfigSpec]
config Json
teamId String? @map("team_id")
team Team? @relation("TeamToWatermarkTemplate", fields: [teamId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([teamId])
@@map("watermark_templates")
}
model WatermarkFile {
id String @id @default(ulid())
assetId String @map("asset_id")
watermarkConfigId String @map("watermark_config_id")
/// [MediaInfo]
media Json?
status WatermarkFileStatus @default(pending)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
asset Asset @relation("AssetToWatermarkFile", fields: [assetId], references: [id], onDelete: Cascade)
watermarkConfig WatermarkConfig @relation(fields: [watermarkConfigId], references: [id], onDelete: Cascade)
@@unique([assetId, watermarkConfigId])
@@index([watermarkConfigId])
@@map("watermark_files")
}
model Asset {
id String @id @default(ulid())
name String @default("")
nameNgram String[] @default([]) @map("name_ngram")
type AssetType
mediaType String? @map("media_type")
fileCount Int @default(0) @map("file_count")
sizeByte BigInt @default(0) @map("size_byte")
status AssetStatus
transcodeTaskId String? @map("transcode_task_id")
/// [MediaInfo]
media Json?
autofillContext String? @map("autofill_context")
isDeleted Boolean @default(false) @map("is_deleted")
deletedAt DateTime? @map("deleted_at")
sortIndex String? @map("sort_index")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
parentId String? @map("parent_id")
parent Asset? @relation("AssetChildren", fields: [parentId], references: [id])
children Asset[] @relation("AssetChildren")
targetId String? @map("target_id")
target Asset? @relation("SymlinkTarget", fields: [targetId], references: [id])
symlinks Asset[] @relation("SymlinkTarget")
storageKeyId String? @map("storage_key_id")
storageKey StorageKey? @relation(fields: [storageKeyId], references: [id])
metadataValues AssetMetadataValue[] @relation("AssetToMetadataValues")
creatorId String? @map("creator_id")
creator User? @relation("UserToAsset", fields: [creatorId], references: [id])
taskId String? @map("task_id")
task Task? @relation("TaskToAsset", fields: [taskId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToAsset", fields: [projectId], references: [id])
comments AssetComment[] @relation("AssetToComment")
commentAttachments AssetCommentAttachment[] @relation("AssetToCommentAttachment")
notifications Notification[] @relation("AssetToNotification")
embeddings AssetEmbedding[] @relation("AssetToEmbedding")
teamRootFolder Team? @relation("TeamToRootFolder")
projectRootFolder Project? @relation("ProjectToRootFolder")
projectShareRoot Project? @relation("ProjectToShareRoot")
shareLinkRootFolder ShareLink? @relation("ShareLinkToRootFolder")
agentSessions AgentSession[] @relation("AssetToAgentSession")
watermarkFiles WatermarkFile[] @relation("AssetToWatermarkFile")
@@map("assets")
@@index([type])
@@index([status])
@@index([createdAt])
@@index([updatedAt])
@@index([sortIndex])
@@index([isDeleted])
@@index([deletedAt])
@@index([name], name: "assets_name_idx")
@@index([nameNgram], type: Gin)
@@unique([parentId, targetId], name: "parentIdTargetId")
}
model StorageKey {
id String @id @default(ulid())
key String @unique
status StorageKeyStatus @default(active)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assets Asset[]
@@map("storage_keys")
}
model AssetMetadataValue {
id String @id @default(ulid())
assetId String @map("asset_id")
fieldKey String @map("field_key") // key from MetadataField
stringValue String? @map("string_value")
numberValue Float? @map("number_value")
booleanValue Boolean? @map("boolean_value")
jsonValue Json? @map("json_value")
dateValue DateTime? @map("date_value")
asset Asset @relation("AssetToMetadataValues", fields: [assetId], references: [id], onDelete: Cascade)
@@unique([assetId, fieldKey])
@@index([numberValue])
@@index([stringValue])
@@index([booleanValue])
@@index([dateValue])
@@index([jsonValue], type: Gin)
@@map("asset_metadata_values")
}
model AssetComment {
id String @id @default(ulid())
message String?
/// [AnnotationList]
annotation Json?
second Float?
sessionId String? @map("session_id")
session AgentSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assetId String @map("asset_id")
asset Asset @relation("AssetToComment", fields: [assetId], references: [id], onDelete: Cascade)
creatorId String? @map("creator_id")
creator User? @relation("UserToAssetComment", fields: [creatorId], references: [id])
isCompleted Boolean @default(false) @map("is_completed")
completionLastChangedById String? @map("completion_last_changed_by_id")
completionLastChangedBy User? @relation("UserToAssetCommentCompletionChanged", fields: [completionLastChangedById], references: [id])
replyToId String? @map("reply_to_id")
replyTo AssetComment? @relation("CommentReplies", fields: [replyToId], references: [id], onDelete: Cascade)
replies AssetComment[] @relation("CommentReplies")
attachments AssetCommentAttachment[] @relation("CommentToAttachment")
@@map("asset_comments")
}
model AssetCommentAttachment {
id String @id @default(ulid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
commentId String @map("comment_id")
comment AssetComment @relation("CommentToAttachment", fields: [commentId], references: [id], onDelete: Cascade)
assetId String @map("asset_id")
asset Asset @relation("AssetToCommentAttachment", fields: [assetId], references: [id], onDelete: Cascade)
@@map("asset_comment_attachments")
}
model AssetEmbedding {
id String @id @default(ulid())
embedding Unsupported("vector(1536)")?
startTime Float? @map("start_time")
endTime Float? @map("end_time")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assetId String @map("asset_id")
asset Asset @relation("AssetToEmbedding", fields: [assetId], references: [id], onDelete: Cascade)
@@index([embedding], name: "AssetEmbedding_embedding_idx")
@@map("asset_embeddings")
}
model Invite {
id String @id @default(ulid())
code String @unique
role InviteRole?
used Boolean @default(false)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToInvite", fields: [teamId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToInvite", fields: [projectId], references: [id], onDelete: Cascade)
inviterId String @map("inviter_id")
inviter User @relation("UserToInvite", fields: [inviterId], references: [id])
@@map("invites")
}
model MetadataField {
id String @id @default(ulid())
key String @unique
scope MetadataFieldScope?
/// [FieldConfig]
config Json?
readOnly Boolean @default(false) @map("read_only")
aiAutofill Boolean @default(false) @map("ai_autofill")
description String @default("")
teamId String? @map("team_id")
team Team? @relation("TeamToMetadataField", fields: [teamId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToMetadataField", fields: [projectId], references: [id], onDelete: Cascade)
@@map("metadata_fields")
}
model Notification {
id String @id @default(ulid())
type NotificationType?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToNotification", fields: [teamId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToNotification", fields: [projectId], references: [id], onDelete: Cascade)
creatorId String? @map("creator_id")
creator User? @relation("UserToCreatedNotification", fields: [creatorId], references: [id])
assetId String? @map("asset_id")
asset Asset? @relation("AssetToNotification", fields: [assetId], references: [id], onDelete: Cascade)
taskId String? @map("task_id")
task Task? @relation("TaskToNotification", fields: [taskId], references: [id])
userId String? @map("user_id")
user User? @relation("UserToNotification", fields: [userId], references: [id])
readByMembers TeamMember? @relation("TeamMemberToLastReadNotification")
@@map("notifications")
}
model SystemSettings {
id String @id @default(ulid())
key String @unique
/// [SystemSettingsValue]
value Json?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("system_settings")
@@index([key])
}
model Task {
id String @id @default(ulid())
type TaskType?
status TaskStatus @default(pending)
name String?
total Int?
uploaded Int @default(0)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
creatorId String? @map("creator_id")
creator User? @relation("UserToTask", fields: [creatorId], references: [id])
assets Asset[] @relation("TaskToAsset")
notifications Notification[] @relation("TaskToNotification")
@@map("tasks")
}
model WorkflowTask {
id String @id @default(ulid())
uid String @default(uuid()) @db.Uuid
teamId String? @map("team_id")
projectId String? @map("project_id")
assetId String @map("asset_id")
type WorkflowTaskType?
status WorkflowTaskStatus?
/// [WorkflowTaskPayload]
payload Json?
/// [WorkflowTaskOutput]
output Json?
heartbeat DateTime?
inputTokens Int @default(0) @map("input_tokens")
outputTokens Int @default(0) @map("output_tokens")
model String?
sessionId String? @map("session_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("workflow_tasks")
@@index([status, heartbeat])
@@index([assetId, type])
@@index([teamId])
@@index([projectId])
@@index([type])
@@index([sessionId])
}
enum AgentType {
chat
autofill
embedding
}
enum AgentSessionType {
comment
chat
naming
}
model Agent {
id String @id
user User @relation(fields: [id], references: [id], onDelete: Cascade)
type AgentType
enabled Boolean @default(true)
soul String? @db.Text
providerId String? @map("provider_id")
provider Provider? @relation("ProviderToAgent", fields: [providerId], references: [id], onDelete: SetNull)
modelId String? @map("model_id")
modelRef Model? @relation("ModelToAgent", fields: [modelId], references: [id], onDelete: SetNull)
teamId String @map("team_id")
team Team @relation("TeamToAgent", fields: [teamId], references: [id], onDelete: Cascade)
/// [AgentConfig]
config Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
agentSessions AgentSession[]
skills AgentSkill[]
mcpServers AgentMcpServer[]
@@map("agents")
}
model AgentSkill {
id String @id @default(ulid())
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
skillId String @map("skill_id")
skill Skill @relation(fields: [skillId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@unique([agentId, skillId])
@@map("agent_skills")
}
model McpServer {
id String @id @default(ulid())
name String
description String?
instructions String?
url String
transport McpTransport @default(streamable_http)
/// [McpServerAuthConfig]
authConfig Json? @default("{}")
/// [McpServerConfig]
config Json? @default("{}")
permission TeamMemberRole @default(reviewer)
/// [McpToolInfo[]]
tools Json? @default("[]")
status String @default("not_connected")
lastError String? @map("last_error")
lastConnectedAt DateTime? @map("last_connected_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToMcpServer", fields: [teamId], references: [id], onDelete: Cascade)
credential McpServerCredential?
agentMcpServers AgentMcpServer[]
@@map("mcp_servers")
}
// Join table: which agents get which MCP servers (mirrors AgentSkill).
model AgentMcpServer {
id String @id @default(ulid())
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
mcpServerId String @map("mcp_server_id")
mcpServer McpServer @relation(fields: [mcpServerId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@unique([agentId, mcpServerId])
@@map("agent_mcp_servers")
}
model McpServerCredential {
id String @id @default(ulid())
serverId String @unique @map("server_id")
server McpServer @relation(fields: [serverId], references: [id], onDelete: Cascade)
serverUrl String @map("server_url")
/// [McpStoredTokens]
tokens Json?
/// [McpStoredClientInfo]
clientInfo Json?
codeVerifier String? @map("code_verifier")
oauthState String? @map("oauth_state")
/// [McpPendingAuth]
pendingAuth Json? @map("pending_auth")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("mcp_server_credentials")
}
enum McpTransport {
streamable_http
sse
}
model AgentSession {
id String @id @default(ulid())
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
userId String? @map("user_id")
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
cwd String
leafId String? @map("leaf_id")
assetId String? @map("asset_id")
asset Asset? @relation("AssetToAgentSession", fields: [assetId], references: [id], onDelete: SetNull)
userCommentId String? @map("user_comment_id")
type AgentSessionType @default(comment)
name String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
entries AgentSessionEntry[]
comments AssetComment[]
@@index([type])
@@map("agent_sessions")
}
model AgentSessionEntry {
id String @id // Uses ULID generated by pi-coding-agent
sessionId String? @map("session_id")
session AgentSession? @relation(fields: [sessionId], references: [id], onDelete: Cascade)
assetId String? @map("asset_id")
type String?
parentId String? @map("parent_id")
/// [PiSessionEntryData]
data Json?
createdAt DateTime @default(now()) @map("created_at")
@@index([sessionId])
@@index([parentId])
@@index([assetId])
@@map("agent_session_entries")
}
model UserMetadata {
id String @id @default(ulid())
key String
/// [UserMetadataValue]
value Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
userId String @map("user_id")
user User @relation("UserToUserMetadata", fields: [userId], references: [id], onDelete: Cascade)
teamId String @map("team_id")
team Team @relation("TeamToUserMetadata", fields: [teamId], references: [id], onDelete: Cascade)
@@unique([userId, teamId, key], name: "userIdTeamIdKey")
@@map("user_metadata")
}
model Model {
id String @id @default(ulid())
modelId String @map("model_id")
name String @default("")
/// [ModelConfig]
config Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
providerId String @map("provider_id")
provider Provider @relation("ProviderToModel", fields: [providerId], references: [id], onDelete: Cascade)
agents Agent[] @relation("ModelToAgent")
@@unique([providerId, modelId])
@@map("models")
}
model Provider {
id String @id @default(ulid())
name String
isBuiltin Boolean @default(false) @map("is_builtin")
/// [ProviderConfig]
config Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToProvider", fields: [teamId], references: [id], onDelete: Cascade)
models Model[] @relation("ProviderToModel")
agents Agent[] @relation("ProviderToAgent")
@@unique([teamId, name])
@@map("providers")
}
model Collection {
id String @id @default(ulid())
name String
/// [CollectionFilter]
filter Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation("ProjectToCollection", fields: [projectId], references: [id], onDelete: Cascade)
creatorId String? @map("creator_id")
creator User? @relation("UserToCollection", fields: [creatorId], references: [id])
@@index([projectId, createdAt(sort: Desc)])
@@map("collections")
}
model ApiToken {
id String @id @default(ulid())
token String @unique @default(ulid())
name String
userId String @map("user_id")
user User @relation("UserToApiToken", fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("api_tokens")
}
model AiUsage {
id String @id @default(ulid())
teamId String @map("team_id")
userId String? @map("user_id")
periodStart DateTime @map("period_start")
inputTokens BigInt @default(0) @map("input_tokens")
outputTokens BigInt @default(0) @map("output_tokens")
cacheReadTokens BigInt @default(0) @map("cache_read_tokens")
totalTokens BigInt @default(0) @map("total_tokens")
cost Float @default(0) @map("cost")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
team Team @relation("TeamToAiUsage", fields: [teamId], references: [id], onDelete: Cascade)
user User? @relation("UserToAiUsage", fields: [userId], references: [id], onDelete: SetNull)
@@map("ai_usages")
@@unique([teamId, userId, periodStart])
@@index([teamId, periodStart])
@@index([teamId, userId, periodStart])
}
model AuditLog {
id String @id @default(ulid())
action String
teamId String @map("team_id")
userId String? @map("user_id")
projectId String? @map("project_id")
itemId String? @map("item_id")
createdAt DateTime @default(now()) @map("created_at")
team Team @relation("TeamToAuditLog", fields: [teamId], references: [id], onDelete: Cascade)
user User? @relation("UserToAuditLog", fields: [userId], references: [id], onDelete: SetNull)
project Project? @relation("ProjectToAuditLog", fields: [projectId], references: [id], onDelete: SetNull)
@@index([teamId, id(sort: Desc)])
@@index([userId])
@@index([action])
@@index([itemId])
@@map("audit_logs")
}