Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): cleaned up view permissions sheet (#49144)

kemal.earthdbb153042eaa
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
index 4aab626e393..7b7e03a3a27 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
- computeOverallRisk,
countConfigured,
getCatalogEntry,
scopesToSelection,
@@ -12,6 +11,7 @@ import {
getEnabledEndpoints,
getEnabledEndpointsForCapability,
getEnabledMcpTools,
+ getEnabledMcpToolsForCapability,
normalizePermissionScopeMap,
type PermissionScopeMap,
} from '@/data/scoped-access-tokens/permission-scope-map-query'
@@ -145,37 +145,6 @@ describe('selectionToScopes', () => {
})
})
-describe('computeOverallRisk', () => {
- it('is Minimal with no capabilities', () => {
- expect(computeOverallRisk({}, 'project').level).toBe('Minimal')
- })
-
- it('account-level read-only is still Elevated', () => {
- const risk = computeOverallRisk({ 'project:advisors': 'read' }, 'account')
- expect(risk.level).toBe('Elevated')
- expect(risk.tone).toBe('medium')
- })
-
- it('account-level with any write is High', () => {
- const risk = computeOverallRisk({ 'project:realtime_config': 'readwrite' }, 'account')
- expect(risk.level).toBe('High')
- })
-
- it('project high-risk write is High', () => {
- expect(computeOverallRisk({ 'project:database': 'readwrite' }, 'project').level).toBe('High')
- })
-
- it('project medium write is Medium', () => {
- expect(computeOverallRisk({ 'project:realtime_config': 'readwrite' }, 'project').level).toBe(
- 'Medium'
- )
- })
-
- it('read-only project is Low', () => {
- expect(computeOverallRisk({ 'project:database': 'read' }, 'project').level).toBe('Low')
- })
-})
-
describe('countConfigured', () => {
it('counts only non-none modes', () => {
expect(countConfigured({ a: 'read', b: 'none', c: 'readwrite' })).toBe(2)
@@ -341,3 +310,64 @@ describe('getEnabledEndpointsForCapability', () => {
).toEqual(['PUT /api/upgrade'])
})
})
+
+describe('getEnabledMcpToolsForCapability', () => {
+ it('attributes a tool to each capability whose scope is in a fully-granted group', () => {
+ const permissionScopeMap = scopeMap({
+ mcp_tools: {
+ list_branches: [['branching_development_read'], ['branching_production_read']],
+ },
+ })
+ const allGrantedScopes = ['branching_development_read', 'branching_production_read']
+
+ expect(
+ getEnabledMcpToolsForCapability({
+ capabilityScopes: ['branching_development_read'],
+ allGrantedScopes,
+ permissionScopeMap,
+ })
+ ).toEqual(['list_branches'])
+ expect(
+ getEnabledMcpToolsForCapability({
+ capabilityScopes: ['branching_production_read'],
+ allGrantedScopes,
+ permissionScopeMap,
+ })
+ ).toEqual(['list_branches'])
+ })
+
+ it('does not attribute a tool to a capability whose own group is unsatisfied', () => {
+ const enabled = getEnabledMcpToolsForCapability({
+ capabilityScopes: ['branching_production_read'],
+ allGrantedScopes: ['branching_development_read'],
+ permissionScopeMap: scopeMap({
+ mcp_tools: {
+ list_branches: [['branching_development_read'], ['branching_production_read']],
+ },
+ }),
+ })
+
+ expect(enabled).toEqual([])
+ })
+
+ it('requires every scope of the capability group to be granted', () => {
+ const permissionScopeMap = scopeMap({
+ mcp_tools: { upgrade_project: [['project_admin_read', 'database_read']] },
+ })
+
+ expect(
+ getEnabledMcpToolsForCapability({
+ capabilityScopes: ['database_read'],
+ allGrantedScopes: ['database_read'],
+ permissionScopeMap,
+ })
+ ).toEqual([])
+ expect(
+ getEnabledMcpToolsForCapability({
+ capabilityScopes: ['database_read'],
+ allGrantedScopes: ['database_read', 'project_admin_read'],
+ permissionScopeMap,
+ })
+ ).toEqual(['upgrade_project'])
+ })
+})
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
index 4b74ad622da..405b96e3d61 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
@@ -629,72 +629,10 @@ export const PERMISSION_MODE_LABEL: Record<PermissionMode, string> = {
readwrite: 'Read-write',
}
-export const RISK_DOT_CLASS: Record<RiskLevel, string> = {
- low: 'bg-brand-600',
- medium: 'bg-warning-600',
- high: 'bg-destructive-600',
-}
-
export type ResourceAccessMode = 'project' | 'organization' | 'account'
-export interface OverallRisk {
- /** Minimal | Low | Medium | Elevated | High */
- level: string
- text: string
- tone: 'default' | 'low' | 'medium' | 'high'
-}
-
-export const RISK_TONE_VARIANT: Record<
- OverallRisk['tone'],
- 'default' | 'success' | 'warning' | 'destructive'
-> = {
- default: 'default',
+export const RISK_TONE_VARIANT: Record<RiskLevel, 'success' | 'warning' | 'destructive'> = {
low: 'success',
medium: 'warning',
high: 'destructive',
}
-
-/**
- * Computes the overall token risk from the selected capabilities and the resource-access breadth.
- * Account-level tokens are never below "Elevated", even when read-only.
- */
-export const computeOverallRisk = (
- selection: PermissionSelection,
- resourceAccess: ResourceAccessMode
-): OverallRisk => {
- const active = Object.entries(selection).filter(([, mode]) => mode !== 'none')
- if (active.length === 0) {
- return { level: 'Minimal', text: 'Minimal — No capabilities', tone: 'default' }
- }
-
- const anyWrite = active.some(([, mode]) => mode === 'readwrite')
- const anyHighWrite = active.some(
- ([key, mode]) => mode === 'readwrite' && CATALOG_BY_KEY.get(key)?.risk === 'high'
- )
-
- const scopeWord =
- resourceAccess === 'account'
- ? 'Account-wide'
- : resourceAccess === 'organization'
- ? 'Organization-wide'
- : 'Single-project'
- const accessWord = anyWrite ? 'read-write' : 'read-only'
-
- let level: string
- let tone: OverallRisk['tone']
- if (resourceAccess === 'account') {
- level = anyWrite ? 'High' : 'Elevated'
- tone = anyWrite ? 'high' : 'medium'
- } else if (anyHighWrite) {
- level = 'High'
- tone = 'high'
- } else if (anyWrite) {
- level = 'Medium'
- tone = 'medium'
- } else {
- level = 'Low'
- tone = 'low'
- }
-
- return { level, text: `${level} — ${scopeWord} ${accessWord} access`, tone }
-}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
index 25f572efe1b..bf066edfacc 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
@@ -1,9 +1,20 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import { ChevronRight } from 'lucide-react'
+import { ChevronRight, X } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
-import { Button, Form, ScrollArea, Separator, SheetClose, SheetFooter } from 'ui'
+import {
+ Button,
+ Form,
+ InfoIcon,
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
+ ScrollArea,
+ Separator,
+ SheetClose,
+ SheetFooter,
+} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { CLASSIC_TOKEN_WARNING } from '../../AccessToken.constants'
@@ -46,6 +57,8 @@ export const NewScopedTokenForm = ({
})
const [step, setStep] = useState<'form' | 'review'>('form')
const [formValues, setFormValues] = useState<TokenFormValues>(DEFAULT_VALUES)
+ // Dismissal sticks for the sheet's lifetime, so bouncing between steps doesn't resurface it.
+ const [isCreateHintDismissed, setIsCreateHintDismissed] = useState(false)
const [showMissingPermissionsWarning, setShowMissingPermissionsWarning] = useState(false)
const resourceSectionRef = useRef<HTMLDivElement>(null)
const resourceAccess = useWatch({ control: form.control, name: 'resourceAccess' })
@@ -111,7 +124,10 @@ export const NewScopedTokenForm = ({
return (
<>
- <ScrollArea className="flex-1">
+ {/* Radix wraps viewport children in an inline-styled display:table div that grows to fit
+ the widest child, which would let one long endpoint path expand the sheet instead of
+ clipping — force it back to block so widths are bounded and rows can truncate. */}
+ <ScrollArea className="flex-1 [&>[data-radix-scroll-area-viewport]>div]:block!">
{step === 'form' ? (
<Form {...form}>
<form id={FORM_ID} onSubmit={form.handleSubmit(handleReviewAccess)}>
@@ -187,16 +203,11 @@ export const NewScopedTokenForm = ({
) : (
<StepIndicator step={step === 'form' ? 1 : 2} total={2} label="Configure" />
)}
- <div className="flex items-center gap-3">
+ <div className="flex items-center gap-2">
{step === 'review' && (
- <>
- <span className="text-xs text-foreground-lighter">
- Access can't be changed after creation
- </span>
- <Button variant="default" disabled={isPending} onClick={() => setStep('form')}>
- Back
- </Button>
- </>
+ <Button variant="default" disabled={isPending} onClick={() => setStep('form')}>
+ Back
+ </Button>
)}
<SheetClose asChild disabled={isPending}>
<Button variant="default">Cancel</Button>
@@ -212,9 +223,35 @@ export const NewScopedTokenForm = ({
</Button>
)}
{step === 'review' && (
- <Button loading={isPending} onClick={() => onCreateToken(formValues)}>
- Create token
- </Button>
+ <Popover open={!isCreateHintDismissed}>
+ <PopoverAnchor asChild>
+ <Button loading={isPending} onClick={() => onCreateToken(formValues)}>
+ Create token
+ </Button>
+ </PopoverAnchor>
+ <PopoverContent
+ side="top"
+ align="end"
+ sideOffset={8}
+ className="flex w-auto items-center gap-2 py-1.5 pl-3 pr-1.5"
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ onInteractOutside={() => setIsCreateHintDismissed(true)}
+ onEscapeKeyDown={() => setIsCreateHintDismissed(true)}
+ >
+ <InfoIcon className="h-5 w-5 shrink-0" />
+ <p className="text-xs text-foreground-light">
+ Access can't be changed after creation
+ </p>
+ <Button
+ variant="text"
+ size="tiny"
+ icon={<X />}
+ aria-label="Dismiss"
+ className="px-1 text-foreground-lighter"
+ onClick={() => setIsCreateHintDismissed(true)}
+ />
+ </PopoverContent>
+ </Popover>
)}
</div>
</SheetFooter>
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
index 3f71e882fb7..2894159cb00 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
@@ -1,12 +1,9 @@
import dayjs from 'dayjs'
-import { useMemo } from 'react'
+import { useMemo, useState } from 'react'
+import { cn } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
-import {
- computeOverallRisk,
- PERMISSION_MODE_LABEL,
- selectionToScopes,
-} from '../../AccessToken.permissions'
+import { PERMISSION_MODE_LABEL, selectionToScopes } from '../../AccessToken.permissions'
import {
groupFailingResources,
TOKEN_ROLE_LABEL,
@@ -15,7 +12,19 @@ import {
import { useCapabilitySummary } from '../../hooks/useCapabilitySummary'
import { useOrgAndProjectData } from '../../hooks/useOrgAndProjectData'
import { failingResourceLine } from '../ExceedsRoleBadge'
-import { CapabilityCategoryList, ResourceSummaryItem, RiskLevelSummary } from '../TokenSummaryRows'
+import {
+ ResourceAccessPills,
+ useResourceAccessWrap,
+ type ResourceAccessPillItem,
+} from '../ResourceAccessPills'
+import { CapabilitiesSection } from '../TokenCapabilities/CapabilitiesSection'
+import { CapabilityLevelToggle } from '../TokenCapabilities/CapabilityLevelToggle'
+import { RiskBanner } from '../TokenCapabilities/RiskBanner'
+import {
+ computeRiskBanner,
+ getCapabilityDensityTier,
+ type CapabilityLevelFilter,
+} from '../TokenCapabilities/TokenCapabilities.utils'
import { EXPIRY_OPTIONS, type TokenFormValues } from './NewScopedTokenForm.utils'
import { PermissionScopeMap } from '@/data/scoped-access-tokens/permission-scope-map-query'
@@ -25,6 +34,10 @@ interface ReviewStepProps {
permissionScopeMap: PermissionScopeMap | undefined
}
+/**
+ * Mirrors the token view sheet (risk banner, summary, capability cards) so reviewing a token
+ * before creating it looks identical to viewing it afterwards.
+ */
export const NewScopedTokenFormReview = ({
values,
access,
@@ -44,37 +57,27 @@ export const NewScopedTokenFormReview = ({
)
const risk = useMemo(
- () => computeOverallRisk(access.effectiveSelection, values.resourceAccess),
- [access.effectiveSelection, values.resourceAccess]
+ () =>
+ computeRiskBanner({
+ effectiveSelection: access.effectiveSelection,
+ resourceAccess: values.resourceAccess,
+ organizationSlugs: values.organizationSlugs,
+ projectRefs: values.projectRefs,
+ }),
+ [access.effectiveSelection, values.resourceAccess, values.organizationSlugs, values.projectRefs]
)
- const resourceSummary = useMemo(() => {
- if (values.resourceAccess === 'project') {
- const selectedProjects = projects.filter((p) => values.projectRefs.includes(p.ref))
- return {
- title: 'Projects',
- items:
- selectedProjects.length > 0
- ? selectedProjects.map((p) => ({ key: p.ref, label: p.name, sublabel: p.ref }))
- : [{ key: 'none', label: '-', sublabel: undefined }],
- }
- }
+ // The classic (account) flow skips review entirely, so only org- and project-bound tokens land
+ // here.
+ const resourceItems = useMemo<ResourceAccessPillItem[]>(() => {
if (values.resourceAccess === 'organization') {
- const selectedOrganizations = organizations.filter((o) =>
- values.organizationSlugs.includes(o.slug)
- )
- return {
- title: 'Organizations',
- items:
- selectedOrganizations.length > 0
- ? selectedOrganizations.map((o) => ({ key: o.slug, label: o.name, sublabel: o.slug }))
- : [{ key: 'none', label: '-', sublabel: undefined }],
- }
- }
- return {
- title: 'Account',
- items: [{ key: 'account', label: 'Account-level access', sublabel: undefined }],
+ return organizations
+ .filter((org) => values.organizationSlugs.includes(org.slug))
+ .map((org) => ({ key: org.slug, label: org.name }))
}
+ return projects
+ .filter((project) => values.projectRefs.includes(project.ref))
+ .map((project) => ({ key: project.ref, label: project.name }))
}, [values, projects, organizations])
const expiresSummary = useMemo(() => {
@@ -86,53 +89,18 @@ export const NewScopedTokenFormReview = ({
return EXPIRY_OPTIONS.find((o) => o.value === values.expiresAt)?.label ?? values.expiresAt
}, [values])
- const hasCapabilities = grantedScopes.length > 0
-
- const { activeByCategory, mcpTools, capabilityGroups } = useCapabilitySummary({
+ const { capabilities } = useCapabilitySummary({
selection,
grantedScopes,
permissionScopeMap,
})
+ const capabilityTier = getCapabilityDensityTier(capabilities.length)
+ const [levelFilter, setLevelFilter] = useState<CapabilityLevelFilter>('all')
- const rows: [string, React.ReactNode][] = [
- ['Name', values.tokenName || <span className="text-foreground-lighter">Untitled token</span>],
- ['Expires', expiresSummary],
- [
- 'Resource access',
- <div key="resource-access" className="space-y-2">
- <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">
- {resourceSummary.title}
- </p>
- <div className="divide-y">
- {resourceSummary.items.map((item) => (
- <ResourceSummaryItem key={item.key} label={item.label} sublabel={item.sublabel} />
- ))}
- </div>
- </div>,
- ],
- [
- 'Capabilities',
- hasCapabilities ? (
- <CapabilityCategoryList categories={activeByCategory} accessEntries={access.entries} />
- ) : (
- <span className="text-foreground-lighter">No capabilities selected</span>
- ),
- ],
- [
- 'Risk level',
- <RiskLevelSummary key="risk" risk={risk} showRoleCaveat={hasExceedingCapabilities} />,
- ],
- ]
+ const { containerRef: pillsRef, isWrapped: isResourceAccessWrapped } = useResourceAccessWrap()
return (
<div className="space-y-6 px-5 sm:px-6 py-6">
- {!hasCapabilities && (
- <Admonition
- type="warning"
- title="This token has no capabilities"
- description="Go back and grant at least one permission before creating it."
- />
- )}
{hasExceedingCapabilities && (
<Admonition
type="warning"
@@ -160,72 +128,54 @@ export const NewScopedTokenFormReview = ({
}
/>
)}
+
<div className="flex flex-col gap-3">
- <h3 className="text-sm">Token summary</h3>
- <dl className="divide-y rounded-md border bg-surface-300">
- {rows.map(([key, value]) => (
- <div key={key} className="grid grid-cols-3 gap-4 px-4 py-3">
- <dt className="text-sm text-foreground-lighter">{key}</dt>
- <dd className="col-span-2 text-sm text-foreground">{value}</dd>
- </div>
- ))}
- </dl>
+ <h3 className="text-sm">Risk assessment</h3>
+ <RiskBanner risk={risk} showRoleCaveat={hasExceedingCapabilities} />
</div>
- {hasCapabilities && (
- <>
- <div className="flex flex-col gap-3">
- <h3 className="text-sm">Management API endpoints enabled</h3>
- {capabilityGroups.length === 0 ? (
- <p className="text-xs text-foreground-light">
- No Management API endpoints are enabled by the selected capabilities.
- </p>
- ) : (
- capabilityGroups.map(({ entry, mode, endpoints }) => (
- <div key={entry.key} className="rounded-md border">
- <div className="flex items-center justify-between border-b bg-surface-100 px-3 py-2">
- <span className="text-xs text-foreground">{entry.name}</span>
- <span className="text-[11px] font-mono uppercase text-foreground-lighter">
- {PERMISSION_MODE_LABEL[mode]}
- </span>
- </div>
- <div className="divide-y">
- {endpoints.map(([method, path]) => (
- <div
- key={`${method} ${path}`}
- className="flex items-center gap-2 px-3 py-1.5 font-mono text-xs"
- >
- <span className="w-14 shrink-0 text-foreground-light">{method}</span>
- <span className="text-foreground">{path}</span>
- </div>
- ))}
- </div>
- </div>
- ))
- )}
+ <div className="flex flex-col gap-3">
+ <h3 className="text-sm">Token summary</h3>
+ <dl className="divide-y rounded-md border bg-surface-300">
+ <div className="flex items-center justify-between gap-4 px-4 py-3">
+ <dt className="shrink-0 text-sm text-foreground-lighter">Name</dt>
+ <dd className="text-sm text-foreground">
+ {values.tokenName || <span className="text-foreground-lighter">Untitled token</span>}
+ </dd>
</div>
-
- <div className="flex flex-col gap-3">
- <h3 className="text-sm">MCP tools</h3>
- {mcpTools.length === 0 ? (
- <p className="text-xs text-foreground-light">
- No MCP tools are enabled by the selected capabilities.
- </p>
- ) : (
- <div className="flex flex-wrap gap-2">
- {mcpTools.map((tool) => (
- <span
- key={tool}
- className="rounded border bg-surface-100 px-2 py-1 font-mono text-xs text-foreground-light"
- >
- {tool}
- </span>
- ))}
- </div>
+ <div className="flex items-center justify-between gap-4 px-4 py-3">
+ <dt className="shrink-0 text-sm text-foreground-lighter">Expires</dt>
+ <dd className="text-sm text-foreground">{expiresSummary}</dd>
+ </div>
+ <div
+ className={cn(
+ 'flex flex-col items-start justify-between gap-4 px-4 py-3 sm:flex-row',
+ isResourceAccessWrapped ? 'sm:items-start' : 'sm:items-center'
)}
+ >
+ <dt className="shrink-0 text-sm text-foreground-lighter">Resource access</dt>
+ <dd className="w-full min-w-0 text-sm text-foreground sm:w-auto sm:flex-1">
+ <div ref={pillsRef} className="flex flex-wrap justify-start gap-1.5 sm:justify-end">
+ <ResourceAccessPills resourceAccess={values.resourceAccess} items={resourceItems} />
+ </div>
+ </dd>
</div>
- </>
- )}
+ </dl>
+ </div>
+
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm">Capabilities</h3>
+ {capabilityTier === 'dense' && (
+ <CapabilityLevelToggle value={levelFilter} onChange={setLevelFilter} />
+ )}
+ </div>
+ <CapabilitiesSection
+ capabilities={capabilities}
+ accessEntries={access.entries}
+ levelFilter={levelFilter}
+ />
+ </div>
</div>
)
}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
index 92c99c051ae..93527687a16 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
@@ -2,20 +2,14 @@ import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import {
RISK_LEVEL_LABEL,
+ RISK_TONE_VARIANT,
type PermissionCatalogEntry,
- type RiskLevel,
} from '../../AccessToken.permissions'
import {
getMcpToolsForScopes,
PermissionScopeMap,
} from '@/data/scoped-access-tokens/permission-scope-map-query'
-const RISK_VARIANT: Record<RiskLevel, 'success' | 'warning' | 'destructive'> = {
- low: 'success',
- medium: 'warning',
- high: 'destructive',
-}
-
interface RiskMarkerProps {
entry: PermissionCatalogEntry
/** When false, renders the dot + label without the explanatory tooltip (used in the review list). */
@@ -32,7 +26,7 @@ export const RiskMarker = ({
}: RiskMarkerProps) => {
const marker = (
<Badge
- variant={RISK_VARIANT[entry.risk]}
+ variant={RISK_TONE_VARIANT[entry.risk]}
className={cn(withTooltip && 'cursor-help', className)}
>
{RISK_LEVEL_LABEL[entry.risk]}
@@ -52,7 +46,7 @@ export const RiskMarker = ({
<span tabIndex={0}>{marker}</span>
</TooltipTrigger>
<TooltipContent side="top" align="center" className="w-72 space-y-2 p-3">
- <Badge variant={RISK_VARIANT[entry.risk]}>{RISK_LEVEL_LABEL[entry.risk]}</Badge>
+ <Badge variant={RISK_TONE_VARIANT[entry.risk]}>{RISK_LEVEL_LABEL[entry.risk]}</Badge>
<p className="text-xs text-foreground-light">{entry.riskReason}</p>
{(entry.allowsRead.length > 0 || entry.allowsWrite.length > 0) && (
<div className="flex flex-col gap-5 mt-5">
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx
index a1c401f7170..550295bac60 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx
@@ -189,9 +189,9 @@ describe('NewScopedTokenSheet', () => {
fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))
fireEvent.click(await screen.findByRole('option', { name: 'Read' }))
fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))
- // Review screen
- await screen.findByText('Low Risk')
- await screen.findByText('Single-project read-only access')
+ // Review screen — Project Settings is a high-risk entry, downgraded one tier for read-only
+ await screen.findByText('Medium risk')
+ await screen.findByText('Read on 1 capability, across 1 project.')
fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))
// If we can click this checkbox, the token was created
// Must be a real click, which focuses the button: nothing holds focus once the form
@@ -239,9 +239,9 @@ describe('NewScopedTokenSheet', () => {
fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))
fireEvent.click(await screen.findByRole('option', { name: 'Read' }))
fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))
- // Review screen
- await screen.findByText('Low Risk')
- await screen.findByText('Organization-wide read-only access')
+ // Review screen — Project Settings is a high-risk entry, downgraded one tier for read-only
+ await screen.findByText('Medium risk')
+ await screen.findByText('Read on 1 capability, across 1 organization.')
fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))
// If we can click this checkbox, the token was created
// Must be a real click, which focuses the button: nothing holds focus once the form
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ResourceAccessPills.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ResourceAccessPills.tsx
new file mode 100644
index 00000000000..568fb8af78b
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ResourceAccessPills.tsx
@@ -0,0 +1,80 @@
+import { Box, Boxes } from 'lucide-react'
+import { useEffect, useRef, useState } from 'react'
+import { cn } from 'ui'
+
+import type { ResourceAccessMode } from '../AccessToken.permissions'
+
+export interface ResourceAccessPillItem {
+ key: string
+ label: string
+ isInaccessible?: boolean
+}
+
+interface ResourceAccessPillsProps {
+ resourceAccess: ResourceAccessMode
+ items: ResourceAccessPillItem[]
+ /** Shown when there are no items — only the caller knows why the list is empty. */
+ emptyText?: string
+}
+
+/** The org/project badges in a token summary's "Resource access" row. */
+export const ResourceAccessPills = ({
+ resourceAccess,
+ items,
+ emptyText = '-',
+}: ResourceAccessPillsProps) => {
+ if (items.length === 0) {
+ return <span className="text-xs text-foreground-lighter">{emptyText}</span>
+ }
+
+ return (
+ <>
+ {items.map((item) => (
+ <div
+ key={item.key}
+ className={cn(
+ 'flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border bg-surface-75 text-foreground-light px-3 py-1 text-xs',
+ item.isInaccessible
+ ? 'border-destructive-500 text-destructive'
+ : 'border-strong text-foreground'
+ )}
+ >
+ {resourceAccess === 'organization' ? (
+ <Boxes size={14} strokeWidth={1.5} className="shrink-0 text-foreground-lighter" />
+ ) : resourceAccess === 'project' ? (
+ <Box size={14} strokeWidth={1.5} className="shrink-0 text-foreground-lighter" />
+ ) : null}
+ {item.label}
+ </div>
+ ))}
+ </>
+ )
+}
+
+/**
+ * Whether the pill container has wrapped onto multiple lines. Vertically centering the row only
+ * reads right when its badges fit on a single line — with wrapped badges the label should sit at
+ * the top instead. Measured, not guessed from item count, since wrapping depends on the sheet's
+ * width and each badge's label length.
+ */
+export const useResourceAccessWrap = () => {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const [isWrapped, setIsWrapped] = useState(false)
+
+ useEffect(() => {
+ const container = containerRef.current
+ if (!container) return
+
+ const checkWrapped = () => {
+ const firstBadge = container.firstElementChild as HTMLElement | null
+ setIsWrapped(firstBadge !== null && container.clientHeight > firstBadge.clientHeight + 2)
+ }
+
+ checkWrapped()
+ const observer = new ResizeObserver(checkWrapped)
+ observer.observe(container)
+ return () => observer.disconnect()
+ }, [])
+
+ return { containerRef, isWrapped }
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilitiesSection.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilitiesSection.tsx
new file mode 100644
index 00000000000..5b34c84c291
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilitiesSection.tsx
@@ -0,0 +1,54 @@
+import { Accordion } from 'ui'
+
+import type { EntryAccess } from '../../AccessToken.roles'
+import type { CapabilitySummaryEntry } from '../../hooks/useCapabilitySummary'
+import { CapabilityCard } from './CapabilityCard'
+import { DenseCapabilities } from './DenseCapabilities'
+import { getCapabilityDensityTier, type CapabilityLevelFilter } from './TokenCapabilities.utils'
+
+interface CapabilitiesSectionProps {
+ capabilities: CapabilitySummaryEntry[]
+ accessEntries: Record<string, EntryAccess>
+ /** Dense tier's All/Read/Read-write control, rendered by the caller next to the section title. */
+ levelFilter: CapabilityLevelFilter
+}
+
+/**
+ * Switches capability presentation on granted count: a moderate number render as a single
+ * closed-by-default accordion, and a large grant switches to the dense, filterable view.
+ */
+export const CapabilitiesSection = ({
+ capabilities,
+ accessEntries,
+ levelFilter,
+}: CapabilitiesSectionProps) => {
+ if (capabilities.length === 0) {
+ return <span className="text-sm text-foreground-lighter">No capabilities selected</span>
+ }
+
+ const tier = getCapabilityDensityTier(capabilities.length)
+
+ if (tier === 'accordion') {
+ return (
+ <Accordion type="multiple">
+ {capabilities.map((capability, index) => (
+ <CapabilityCard
+ key={capability.entry.key}
+ capability={capability}
+ accessEntries={accessEntries}
+ isFirst={index === 0}
+ isLast={index === capabilities.length - 1}
+ />
+ ))}
+ </Accordion>
+ )
+ }
+
+ return (
+ <DenseCapabilities
+ capabilities={capabilities}
+ accessEntries={accessEntries}
+ levelFilter={levelFilter}
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityCard.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityCard.tsx
new file mode 100644
index 00000000000..a870fa5fe7e
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityCard.tsx
@@ -0,0 +1,75 @@
+import { AccordionContent, AccordionItem, AccordionTrigger, Badge, cn } from 'ui'
+
+import { PERMISSION_MODE_LABEL } from '../../AccessToken.permissions'
+import type { EntryAccess } from '../../AccessToken.roles'
+import type { CapabilitySummaryEntry } from '../../hooks/useCapabilitySummary'
+import { ExceedsRoleBadge } from '../ExceedsRoleBadge'
+import { CapabilityCardBody } from './CapabilityCardBody'
+import { formatCapabilityCounts } from './TokenCapabilities.utils'
+
+interface CapabilityCardProps {
+ capability: CapabilitySummaryEntry
+ accessEntries: Record<string, EntryAccess>
+ /** Position within the continuous bordered list — controls corner rounding and shared edges. */
+ isFirst?: boolean
+ isLast?: boolean
+}
+
+const CapabilityCardHeader = ({
+ capability,
+ accessEntries,
+}: Pick<CapabilityCardProps, 'capability' | 'accessEntries'>) => {
+ const { entry, mode, endpoints, mcpTools } = capability
+ const entryAccess = accessEntries[entry.key]
+
+ return (
+ <div className="flex flex-1 items-center justify-between gap-2 pr-2">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-medium text-foreground">{entry.name}</span>
+ {entryAccess?.status === 'exceeds-role' && (
+ <ExceedsRoleBadge entry={entry} mode={mode} access={entryAccess} />
+ )}
+ </span>
+ <span className="text-xs text-foreground-lighter">
+ {formatCapabilityCounts(endpoints.length, mcpTools.length)}
+ </span>
+ </div>
+ <Badge variant={mode === 'readwrite' ? 'warning' : 'default'} className="shrink-0">
+ {PERMISSION_MODE_LABEL[mode]}
+ </Badge>
+ </div>
+ )
+}
+
+export const CapabilityCard = ({
+ capability,
+ accessEntries,
+ isFirst = true,
+ isLast = true,
+}: CapabilityCardProps) => {
+ const body = (
+ <CapabilityCardBody
+ entry={capability.entry}
+ endpoints={capability.endpoints}
+ mcpTools={capability.mcpTools}
+ />
+ )
+ const positionClassName = cn(
+ 'border',
+ !isLast && 'border-b-0',
+ isFirst && 'rounded-t-md',
+ isLast && 'rounded-b-md'
+ )
+
+ return (
+ <AccordionItem value={capability.entry.key} className={positionClassName}>
+ <AccordionTrigger className="bg-surface-300 px-4 py-3 transition first:rounded-t last:rounded-b hover:no-underline">
+ <CapabilityCardHeader capability={capability} accessEntries={accessEntries} />
+ </AccordionTrigger>
+ <AccordionContent className="*:pb-0">
+ <div className="px-4 pb-4">{body}</div>
+ </AccordionContent>
+ </AccordionItem>
+ )
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityCardBody.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityCardBody.tsx
new file mode 100644
index 00000000000..2084fbf5740
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityCardBody.tsx
@@ -0,0 +1,69 @@
+import { Badge } from 'ui'
+
+import {
+ RISK_LEVEL_LABEL,
+ RISK_TONE_VARIANT,
+ type PermissionCatalogEntry,
+} from '../../AccessToken.permissions'
+import { EndpointRow } from './EndpointRow'
+import { getSharedPathPrefix } from './TokenCapabilities.utils'
+import type { EnabledEndpoint } from '@/data/scoped-access-tokens/permission-scope-map-query'
+
+interface CapabilityCardBodyProps {
+ entry: PermissionCatalogEntry
+ endpoints: EnabledEndpoint[]
+ mcpTools: string[]
+}
+
+export const CapabilityCardBody = ({ entry, endpoints, mcpTools }: CapabilityCardBodyProps) => {
+ const sharedPrefix = getSharedPathPrefix(endpoints.map((endpoint) => endpoint.path))
+ const methodColumnWidth = `${Math.max(0, ...endpoints.map((endpoint) => endpoint.method.length)) + 2}ch`
+
+ return (
+ <div className="flex flex-col gap-4 mt-4">
+ <div className="flex flex-col gap-1.5">
+ <h3 className="text-xs tracking-wide text-foreground-lighter">Description</h3>
+ <p className="text-sm text-foreground">{entry.description}</p>
+ </div>
+
+ <div className="flex flex-col items-start gap-1.5">
+ <h3 className="text-xs tracking-wide text-foreground-lighter">Risk Level</h3>
+ <Badge variant={RISK_TONE_VARIANT[entry.risk]}>{RISK_LEVEL_LABEL[entry.risk]}</Badge>
+ </div>
+
+ {endpoints.length > 0 && (
+ <div className="flex flex-col gap-1.5">
+ <h3 className="text-xs tracking-wide text-foreground-lighter">API endpoints</h3>
+ <div className="divide-y">
+ {endpoints.map((endpoint) => (
+ <EndpointRow
+ key={endpoint.raw}
+ method={endpoint.method}
+ path={endpoint.path}
+ sharedPrefix={sharedPrefix}
+ methodColumnWidth={methodColumnWidth}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ {mcpTools.length > 0 && (
+ <div className="flex flex-col gap-1.5">
+ <h3 className="text-xs tracking-wide text-foreground-lighter">MCP tools</h3>
+ <div className="flex flex-wrap gap-1.5">
+ {mcpTools.map((tool) => (
+ <Badge key={tool} variant="default">
+ {tool}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+ {endpoints.length === 0 && mcpTools.length === 0 && (
+ <p className="text-xs text-foreground-lighter">
+ No API endpoints or MCP tools are enabled by this capability yet.
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityLevelToggle.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityLevelToggle.tsx
new file mode 100644
index 00000000000..e2306e9cd04
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/CapabilityLevelToggle.tsx
@@ -0,0 +1,43 @@
+import { Button, cn } from 'ui'
+
+import type { CapabilityLevelFilter } from './TokenCapabilities.utils'
+
+interface CapabilityLevelToggleProps {
+ value: CapabilityLevelFilter
+ onChange: (value: CapabilityLevelFilter) => void
+}
+
+const OPTIONS: { value: CapabilityLevelFilter; label: string }[] = [
+ { value: 'all', label: 'All' },
+ { value: 'read', label: 'Read' },
+ { value: 'readwrite', label: 'Read-write' },
+]
+
+/**
+ * Segmented control matching the "Show all / Error only" pattern from Auth's UserLogs: adjacent
+ * Buttons with their variant swapped on selection, glued together via rounding/border removal
+ * and a thin divider, rather than a dedicated segmented-control primitive.
+ */
+export const CapabilityLevelToggle = ({ value, onChange }: CapabilityLevelToggleProps) => (
+ <div className="flex items-center">
+ {OPTIONS.map(({ value: optionValue, label }, index) => (
+ <div key={optionValue} className="flex items-center">
+ {index > 0 && <div className="border-button border border-l-0 py-3" />}
+ <Button
+ type="button"
+ size="tiny"
+ variant={value === optionValue ? 'secondary' : 'default'}
+ aria-pressed={value === optionValue}
+ className={cn(
+ index === 0 && 'rounded-r-none border-r-0',
+ index === OPTIONS.length - 1 && 'rounded-l-none border-l-0',
+ index > 0 && index < OPTIONS.length - 1 && 'rounded-none border-x-0'
+ )}
+ onClick={() => onChange(optionValue)}
+ >
+ {label}
+ </Button>
+ </div>
+ ))}
+ </div>
+)
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/DenseCapabilities.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/DenseCapabilities.tsx
new file mode 100644
index 00000000000..c9fa7f5073f
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/DenseCapabilities.tsx
@@ -0,0 +1,72 @@
+import { useState } from 'react'
+import { Accordion, Badge } from 'ui'
+
+import type { EntryAccess } from '../../AccessToken.roles'
+import type { CapabilitySummaryEntry } from '../../hooks/useCapabilitySummary'
+import { CapabilityCard } from './CapabilityCard'
+import {
+ getNotGrantedCatalogEntries,
+ groupCapabilitiesByLevel,
+ type CapabilityLevelFilter,
+} from './TokenCapabilities.utils'
+
+interface DenseCapabilitiesProps {
+ capabilities: CapabilitySummaryEntry[]
+ accessEntries: Record<string, EntryAccess>
+ /** Which level group(s) to show — the All/Read/Read-write control lives next to the section title. */
+ levelFilter: CapabilityLevelFilter
+}
+
+/** 9+ capabilities: a level-grouped list, read-write pinned first. */
+export const DenseCapabilities = ({
+ capabilities,
+ accessEntries,
+ levelFilter,
+}: DenseCapabilitiesProps) => {
+ const [openKeys, setOpenKeys] = useState<string[]>([])
+
+ const { readwrite, read } = groupCapabilitiesByLevel(capabilities)
+ const notGranted = getNotGrantedCatalogEntries(capabilities)
+
+ const shown =
+ levelFilter === 'readwrite'
+ ? readwrite
+ : levelFilter === 'read'
+ ? read
+ : [...readwrite, ...read]
+
+ return (
+ <div className="flex flex-col gap-4">
+ {shown.length === 0 && (
+ <p className="text-xs text-foreground-lighter">No capabilities match this filter.</p>
+ )}
+
+ <Accordion type="multiple" value={openKeys} onValueChange={setOpenKeys}>
+ {shown.map((capability, index) => (
+ <CapabilityCard
+ key={capability.entry.key}
+ capability={capability}
+ accessEntries={accessEntries}
+ isFirst={index === 0}
+ isLast={index === shown.length - 1}
+ />
+ ))}
+ </Accordion>
+
+ {notGranted.length > 0 && (
+ <div className="flex flex-col gap-2">
+ <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">
+ Not granted · {notGranted.length}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {notGranted.map((entry) => (
+ <Badge key={entry.key} variant="default">
+ {entry.name}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/EndpointRow.test.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/EndpointRow.test.tsx
new file mode 100644
index 00000000000..00ccd311b1d
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/EndpointRow.test.tsx
@@ -0,0 +1,29 @@
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, test } from 'vitest'
+
+import { EndpointRow } from './EndpointRow'
+import { customRender } from '@/tests/lib/custom-render'
+
+const user = userEvent.setup({ writeToClipboard: true })
+
+describe('EndpointRow', () => {
+ test('copies the endpoint path on click', async () => {
+ customRender(
+ <EndpointRow
+ method="GET"
+ path="/v1/projects/{ref}/config"
+ sharedPrefix=""
+ methodColumnWidth="5ch"
+ />
+ )
+
+ // Must be a real click, which focuses the button: copyToClipboard bails out when the
+ // document has no focus
+ await user.click(screen.getByRole('button', { name: 'Copy GET /v1/projects/{ref}/config' }))
+
+ await waitFor(async () =>
+ expect(await window.navigator.clipboard.readText()).toBe('/v1/projects/{ref}/config')
+ )
+ })
+})
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/EndpointRow.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/EndpointRow.tsx
new file mode 100644
index 00000000000..bec181ee517
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/EndpointRow.tsx
@@ -0,0 +1,121 @@
+import { Check, Copy } from 'lucide-react'
+import { useEffect, useRef, useState } from 'react'
+import { cn, copyToClipboard } from 'ui'
+
+import { splitEndpointPath } from './TokenCapabilities.utils'
+
+interface EndpointRowProps {
+ method: string
+ path: string
+ /** Shared leading segments across the group, rendered muted ahead of the distinguishing part. */
+ sharedPrefix: string
+ /** Sized by the caller for the longest method present in the group. */
+ methodColumnWidth: string
+}
+
+/** Pan slowly enough to read while revealing (~70px/s), but never snap for short distances. */
+const panDurationMs = (distance: number) => Math.max(300, Math.round(distance * 14))
+
+/**
+ * One copyable endpoint. The muted prefix span shrinks with an end-ellipsis while the
+ * distinguishing segment stays fixed-width — visually equivalent to truncating the full path in
+ * its middle, without needing to measure pixel widths. A distinguishing segment too long for the
+ * row clips at the right instead, so hovering (or focusing) pans the path sideways to bring the
+ * clipped tail into view. Clicking copies the path — the pasteable part; the method is visible
+ * context.
+ */
+export const EndpointRow = ({
+ method,
+ path,
+ sharedPrefix,
+ methodColumnWidth,
+}: EndpointRowProps) => {
+ const { prefix, distinguishing } = splitEndpointPath(path, sharedPrefix)
+
+ const pathContainerRef = useRef<HTMLSpanElement>(null)
+ const [panDistance, setPanDistance] = useState(0)
+ const [isRevealed, setIsRevealed] = useState(false)
+ const [isCopied, setIsCopied] = useState(false)
+ const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
+ const [showCopiedIcon, setShowCopiedIcon] = useState(false)
+
+ useEffect(() => () => clearTimeout(copiedTimerRef.current), [])
+
+ // Measured when the reveal starts, not on mount: rows live inside accordion content that mounts
+ // collapsed, so resting measurements are taken before the row has its real width.
+ const handleRevealStart = () => {
+ const container = pathContainerRef.current
+ if (container) setPanDistance(Math.max(0, container.scrollWidth - container.clientWidth))
+ setIsRevealed(true)
+ }
+ const handleRevealEnd = () => setIsRevealed(false)
+
+ const handleCopy = () => {
+ copyToClipboard(path, () => {
+ setIsCopied(true)
+ setShowCopiedIcon(true)
+ clearTimeout(copiedTimerRef.current)
+ copiedTimerRef.current = setTimeout(() => setShowCopiedIcon(false), 2000)
+ })
+ }
+
+ return (
+ <button
+ type="button"
+ tabIndex={0}
+ onClick={handleCopy}
+ onMouseEnter={handleRevealStart}
+ onMouseLeave={handleRevealEnd}
+ onFocus={handleRevealStart}
+ onBlur={handleRevealEnd}
+ aria-label={`Copy ${method} ${path}`}
+ className="group flex w-full items-center gap-2 py-1.5 text-left"
+ >
+ <span
+ className="shrink-0 font-mono text-xs text-foreground-lighter"
+ style={{ width: methodColumnWidth }}
+ >
+ {method}
+ </span>
+ <span
+ ref={pathContainerRef}
+ className={cn(
+ 'flex min-w-0 flex-1 overflow-hidden whitespace-nowrap font-mono text-xs',
+ // The fade only paints over text that reaches the container's right edge, so short rows
+ // are unaffected; dropped while panning so the revealed tail stays readable.
+ !isRevealed && '[mask-image:linear-gradient(to_right,black_calc(100%-2rem),transparent)]'
+ )}
+ >
+ <span
+ className="flex min-w-0 transition-transform ease-linear motion-reduce:transition-none"
+ style={{
+ transform:
+ isRevealed && panDistance > 0 ? `translateX(-${panDistance}px)` : 'translateX(0)',
+ // Pausing before panning lets a quick mouse pass leave the row untouched; the pan
+ // back starts immediately and faster, so the row settles as soon as it's left.
+ transitionDuration: isRevealed ? `${panDurationMs(panDistance)}ms` : '200ms',
+ transitionDelay: isRevealed ? '400ms' : '0ms',
+ }}
+ >
+ {prefix !== '' && (
+ <span className="overflow-hidden text-ellipsis text-foreground-lighter">{prefix}</span>
+ )}
+ <span className="shrink-0 text-foreground">{distinguishing}</span>
+ </span>
+ </span>
+ <span className="shrink-0 pl-2">
+ {showCopiedIcon ? (
+ <Check size={14} className="text-brand" />
+ ) : (
+ <Copy
+ size={14}
+ className="text-foreground-lighter opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100"
+ />
+ )}
+ </span>
+ <span className="sr-only" aria-live="polite">
+ {isCopied ? 'URL copied' : null}
+ </span>
+ </button>
+ )
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/RiskBanner.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/RiskBanner.tsx
new file mode 100644
index 00000000000..c4f50328f1a
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/RiskBanner.tsx
@@ -0,0 +1,27 @@
+import { Admonition } from 'ui-patterns/Admonition'
+import type { AdmonitionType } from 'ui-patterns/Admonition'
+
+import type { RiskBannerResult } from './TokenCapabilities.utils'
+
+const TONE_TO_ADMONITION_TYPE: Record<RiskBannerResult['tone'], AdmonitionType> = {
+ default: 'default',
+ low: 'success',
+ medium: 'warning',
+ high: 'destructive',
+}
+
+interface RiskBannerProps {
+ risk: RiskBannerResult
+ /** True when some selected permissions exceed the owner's role, so the risk is role-capped. */
+ showRoleCaveat: boolean
+}
+
+export const RiskBanner = ({ risk, showRoleCaveat }: RiskBannerProps) => (
+ <Admonition
+ type={TONE_TO_ADMONITION_TYPE[risk.tone]}
+ title={`${risk.level} risk`}
+ description={risk.summary}
+ >
+ {showRoleCaveat && 'Based on what your current role allows this token to do.'}
+ </Admonition>
+)
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.constants.ts b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.constants.ts
new file mode 100644
index 00000000000..d6da62c72b3
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.constants.ts
@@ -0,0 +1,5 @@
+/**
+ * Density-tier threshold for the capabilities section, keyed to the number of granted
+ * capabilities. Provisional — revisit with product/design once real tokens exercise it.
+ */
+export const CAPABILITY_DENSITY_ACCORDION_MAX = 8
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.utils.test.ts b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.utils.test.ts
new file mode 100644
index 00000000000..9c9f1a431d6
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.utils.test.ts
@@ -0,0 +1,219 @@
+import { describe, expect, it } from 'vitest'
+
+import { getCatalogEntry } from '../../AccessToken.permissions'
+import type { CapabilitySummaryEntry } from '../../hooks/useCapabilitySummary'
+import {
+ computeRiskBanner,
+ formatCapabilityCounts,
+ getCapabilityDensityTier,
+ getNotGrantedCatalogEntries,
+ getSharedPathPrefix,
+ groupCapabilitiesByLevel,
+ splitEndpointPath,
+} from './TokenCapabilities.utils'
+
+// 'project:database' is catalog-high and writable; 'project:advisors' is catalog-low and read-only.
+const databaseCapability = (
+ mode: CapabilitySummaryEntry['mode'],
+ endpoints: CapabilitySummaryEntry['endpoints'] = []
+): CapabilitySummaryEntry => ({
+ entry: getCatalogEntry('project:database')!,
+ mode,
+ endpoints,
+ mcpTools: [],
+})
+
+const advisorsCapability = (mode: CapabilitySummaryEntry['mode']): CapabilitySummaryEntry => ({
+ entry: getCatalogEntry('project:advisors')!,
+ mode,
+ endpoints: [],
+ mcpTools: [],
+})
+
+describe('formatCapabilityCounts', () => {
+ it('combines both counts when both are non-zero', () => {
+ expect(formatCapabilityCounts(3, 2)).toBe('3 endpoints and 2 MCP tools')
+ })
+
+ it('omits the endpoint side when it is zero', () => {
+ expect(formatCapabilityCounts(0, 2)).toBe('2 MCP tools')
+ })
+
+ it('omits the MCP tool side when it is zero', () => {
+ expect(formatCapabilityCounts(3, 0)).toBe('3 endpoints')
+ })
+
+ it('singularizes a count of one', () => {
+ expect(formatCapabilityCounts(1, 0)).toBe('1 endpoint')
+ expect(formatCapabilityCounts(0, 1)).toBe('1 MCP tool')
+ })
+
+ it('falls back to the endpoint count when both are zero', () => {
+ expect(formatCapabilityCounts(0, 0)).toBe('0 endpoints')
+ })
+})
+
+describe('getCapabilityDensityTier', () => {
+ it('is accordion at 8 or fewer capabilities', () => {
+ expect(getCapabilityDensityTier(0)).toBe('accordion')
+ expect(getCapabilityDensityTier(8)).toBe('accordion')
+ })
+
+ it('is dense at 9 or more capabilities', () => {
+ expect(getCapabilityDensityTier(9)).toBe('dense')
+ expect(getCapabilityDensityTier(50)).toBe('dense')
+ })
+})
+
+describe('getSharedPathPrefix', () => {
+ it('returns nothing for a single endpoint — there is nothing to share', () => {
+ expect(getSharedPathPrefix(['/v1/projects/{ref}'])).toBe('')
+ })
+
+ it('finds the longest shared leading segments across paths', () => {
+ expect(
+ getSharedPathPrefix(['/v1/projects/{ref}/functions', '/v1/projects/{ref}/functions/{slug}'])
+ ).toBe('/v1/projects/{ref}/functions/')
+ })
+
+ it('never cuts a shared prefix mid-segment', () => {
+ // "functions" and "functions-secrets" share characters but not a path segment.
+ expect(
+ getSharedPathPrefix(['/v1/projects/{ref}/functions', '/v1/projects/{ref}/functions-secrets'])
+ ).toBe('/v1/projects/{ref}/')
+ })
+
+ it('shares only the common leading segments, not any further', () => {
+ expect(getSharedPathPrefix(['/v1/branches', '/v1/organizations'])).toBe('/v1/')
+ })
+
+ it('returns nothing when paths share no leading segment at all', () => {
+ expect(getSharedPathPrefix(['/v1/branches', '/v2/organizations'])).toBe('')
+ })
+
+ it('keeps at least the last segment distinguishing when every path is identical', () => {
+ expect(getSharedPathPrefix(['/v1/projects/{ref}', '/v1/projects/{ref}'])).toBe('/v1/projects/')
+ })
+})
+
+describe('splitEndpointPath', () => {
+ it('splits off the shared prefix when the path starts with it', () => {
+ expect(splitEndpointPath('/v1/projects/{ref}/functions', '/v1/projects/{ref}/')).toEqual({
+ prefix: '/v1/projects/{ref}/',
+ distinguishing: 'functions',
+ })
+ })
+
+ it('treats the whole path as distinguishing when there is no shared prefix', () => {
+ expect(splitEndpointPath('/v1/projects/{ref}', '')).toEqual({
+ prefix: '',
+ distinguishing: '/v1/projects/{ref}',
+ })
+ })
+})
+
+describe('groupCapabilitiesByLevel', () => {
+ it('splits granted capabilities into read-write and read-only', () => {
+ const capabilities = [databaseCapability('readwrite'), advisorsCapability('read')]
+
+ const { readwrite, read } = groupCapabilitiesByLevel(capabilities)
+ expect(readwrite.map((c) => c.entry.key)).toEqual(['project:database'])
+ expect(read.map((c) => c.entry.key)).toEqual(['project:advisors'])
+ })
+})
+
+describe('getNotGrantedCatalogEntries', () => {
+ it('returns every catalog entry when nothing is granted', () => {
+ expect(getNotGrantedCatalogEntries([]).map((e) => e.key)).toContain('project:database')
+ })
+
+ it('excludes granted entries', () => {
+ const notGranted = getNotGrantedCatalogEntries([databaseCapability('read')])
+ expect(notGranted.map((e) => e.key)).not.toContain('project:database')
+ })
+})
+
+describe('computeRiskBanner', () => {
+ it('reports Minimal with no active capabilities', () => {
+ const risk = computeRiskBanner({
+ effectiveSelection: {},
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: ['proj-1'],
+ })
+ expect(risk).toEqual({ level: 'Minimal', tone: 'default', summary: 'No capabilities granted.' })
+ })
+
+ it('downgrades a read-only grant so it never outranks read-write on a lower-risk resource', () => {
+ // project:database is catalog-high; read-only downgrades it to medium.
+ const risk = computeRiskBanner({
+ effectiveSelection: { 'project:database': 'read' },
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: ['proj-1'],
+ })
+ expect(risk.level).toBe('Medium')
+ })
+
+ it('takes the max risk across capabilities, not just a write flag', () => {
+ const risk = computeRiskBanner({
+ effectiveSelection: { 'project:database': 'readwrite', 'project:advisors': 'read' },
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: ['proj-1'],
+ })
+ expect(risk.level).toBe('High')
+ })
+
+ it('escalates account-wide read-write access to High', () => {
+ const risk = computeRiskBanner({
+ effectiveSelection: { 'project:advisors': 'readwrite' },
+ resourceAccess: 'account',
+ organizationSlugs: [],
+ projectRefs: [],
+ })
+ expect(risk.level).toBe('High')
+ expect(risk.summary).toContain('across your entire account')
+ })
+
+ it('escalates project scope spanning many bound projects', () => {
+ const narrow = computeRiskBanner({
+ effectiveSelection: { 'project:advisors': 'read' },
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: ['a'],
+ })
+ const broad = computeRiskBanner({
+ effectiveSelection: { 'project:advisors': 'read' },
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: ['a', 'b', 'c', 'd', 'e', 'f'],
+ })
+ expect(narrow.level).toBe('Low')
+ expect(broad.level).toBe('Medium')
+ })
+
+ it('summarizes mixed read and read-write grants with explicit scope breadth', () => {
+ const risk = computeRiskBanner({
+ effectiveSelection: {
+ 'project:database': 'readwrite',
+ 'project:advisors': 'read',
+ 'project:storage': 'read',
+ },
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: ['a', 'b', 'c'],
+ })
+ expect(risk.summary).toBe('Read-write on 1 capability, read on 2, across 3 projects.')
+ })
+
+ it('states scope breadth even when nothing is bound', () => {
+ const risk = computeRiskBanner({
+ effectiveSelection: { 'project:advisors': 'read' },
+ resourceAccess: 'project',
+ organizationSlugs: [],
+ projectRefs: [],
+ })
+ expect(risk.summary).toContain('with no projects bound')
+ })
+})
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.utils.ts b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.utils.ts
new file mode 100644
index 00000000000..266e6c960d2
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenCapabilities/TokenCapabilities.utils.ts
@@ -0,0 +1,157 @@
+import {
+ getCatalogEntry,
+ PERMISSION_CATALOG,
+ type PermissionCatalogEntry,
+ type PermissionSelection,
+ type ResourceAccessMode,
+ type RiskLevel,
+} from '../../AccessToken.permissions'
+import type { CapabilitySummaryEntry } from '../../hooks/useCapabilitySummary'
+import { CAPABILITY_DENSITY_ACCORDION_MAX } from './TokenCapabilities.constants'
+import { pluralize } from '@/lib/helpers'
+
+export type CapabilityDensityTier = 'accordion' | 'dense'
+
+export const getCapabilityDensityTier = (count: number): CapabilityDensityTier =>
+ count <= CAPABILITY_DENSITY_ACCORDION_MAX ? 'accordion' : 'dense'
+
+/** Card subheading counts — omits whichever side is zero rather than saying "and 0 ...". */
+export const formatCapabilityCounts = (endpointCount: number, mcpToolCount: number): string => {
+ const endpointText = `${endpointCount} ${pluralize(endpointCount, 'endpoint')}`
+ const mcpToolText = `${mcpToolCount} MCP ${pluralize(mcpToolCount, 'tool')}`
+
+ if (endpointCount === 0 && mcpToolCount === 0) return endpointText
+ if (endpointCount === 0) return mcpToolText
+ if (mcpToolCount === 0) return endpointText
+ return `${endpointText} and ${mcpToolText}`
+}
+
+/**
+ * Longest shared leading path segments across a group of endpoint paths, so the UI can mute the
+ * boilerplate prefix and highlight only the segment that distinguishes each row. Matching is
+ * segment-aware (split on "/") so a shared prefix never cuts a path mid-segment. A single-endpoint
+ * group has nothing to share, so the whole path is treated as the distinguishing part.
+ */
+export const getSharedPathPrefix = (paths: string[]): string => {
+ if (paths.length < 2) return ''
+
+ const segmentLists = paths.map((path) => path.split('/'))
+ const [first, ...rest] = segmentLists
+ let matched = 0
+ while (matched < first.length && rest.every((segments) => segments[matched] === first[matched])) {
+ matched++
+ }
+ // Every path is identical (not just the shortest one fully consumed as a prefix of a longer
+ // one) — back off one segment so each path keeps at least the last as its distinguishing part.
+ if (segmentLists.every((segments) => segments.length === matched)) matched -= 1
+ // matched === 1 only captures the empty segment before the leading "/", shared trivially by
+ // every absolute path — not a meaningful prefix.
+ if (matched <= 1) return ''
+ return first.slice(0, matched).join('/') + '/'
+}
+
+export const splitEndpointPath = (path: string, sharedPrefix: string) =>
+ sharedPrefix !== '' && path.startsWith(sharedPrefix)
+ ? { prefix: sharedPrefix, distinguishing: path.slice(sharedPrefix.length) }
+ : { prefix: '', distinguishing: path }
+
+export const groupCapabilitiesByLevel = (capabilities: CapabilitySummaryEntry[]) => ({
+ readwrite: capabilities.filter((capability) => capability.mode === 'readwrite'),
+ read: capabilities.filter((capability) => capability.mode === 'read'),
+})
+
+/** Catalog entries the token doesn't grant at all — dense mode's "Not granted" group. */
+export const getNotGrantedCatalogEntries = (
+ capabilities: CapabilitySummaryEntry[]
+): PermissionCatalogEntry[] => {
+ const grantedKeys = new Set(capabilities.map((capability) => capability.entry.key))
+ return PERMISSION_CATALOG.filter((entry) => !grantedKeys.has(entry.key))
+}
+
+export type CapabilityLevelFilter = 'all' | 'read' | 'readwrite'
+
+const RISK_RANK: Record<RiskLevel, number> = { low: 1, medium: 2, high: 3 }
+const RANK_TO_RISK: Record<number, RiskLevel> = { 1: 'low', 2: 'medium', 3: 'high' }
+
+/** One severity tier down, floored at 'low' — a read-only grant never outranks a read-write one. */
+const downgradeRisk = (risk: RiskLevel): RiskLevel => RANK_TO_RISK[Math.max(1, RISK_RANK[risk] - 1)]
+
+export interface RiskBannerResult {
+ level: 'Minimal' | 'Low' | 'Medium' | 'High'
+ tone: 'default' | 'low' | 'medium' | 'high'
+ summary: string
+}
+
+/**
+ * Computes the risk banner from the grant itself, never from a stored string. Severity is a max()
+ * over every granted capability's catalog risk — downgraded a tier for read-only grants so a
+ * read-only high-risk resource never outranks read-write on a medium one — then escalated for
+ * account-wide tokens and resource bindings spanning many orgs/projects.
+ */
+export const computeRiskBanner = ({
+ effectiveSelection,
+ resourceAccess,
+ organizationSlugs,
+ projectRefs,
+}: {
+ effectiveSelection: PermissionSelection
+ resourceAccess: ResourceAccessMode
+ organizationSlugs: string[]
+ projectRefs: string[]
+}): RiskBannerResult => {
+ const active = Object.entries(effectiveSelection).filter(([, mode]) => mode !== 'none')
+
+ if (active.length === 0) {
+ return { level: 'Minimal', tone: 'default', summary: 'No capabilities granted.' }
+ }
+
+ const readWriteCount = active.filter(([, mode]) => mode === 'readwrite').length
+ const readCount = active.length - readWriteCount
+
+ const maxRisk = active.reduce<RiskLevel>((max, [key, mode]) => {
+ const entry = getCatalogEntry(key)
+ if (!entry) return max
+ const effectiveRisk: RiskLevel = mode === 'readwrite' ? entry.risk : downgradeRisk(entry.risk)
+ return RISK_RANK[effectiveRisk] > RISK_RANK[max] ? effectiveRisk : max
+ }, 'low')
+
+ let rank = RISK_RANK[maxRisk]
+ if (resourceAccess === 'account') {
+ rank = Math.max(rank, RISK_RANK.medium) + (readWriteCount > 0 ? 1 : 0)
+ } else if (resourceAccess === 'organization' && organizationSlugs.length > 3) {
+ rank += 1
+ } else if (resourceAccess === 'project' && projectRefs.length > 5) {
+ rank += 1
+ }
+ rank = Math.min(rank, RISK_RANK.high)
+
+ const level = rank === RISK_RANK.high ? 'High' : rank === RISK_RANK.medium ? 'Medium' : 'Low'
+ const tone = rank === RISK_RANK.high ? 'high' : rank === RISK_RANK.medium ? 'medium' : 'low'
+
+ const resourceNoun = resourceAccess === 'organization' ? 'organization' : 'project'
+ const boundCount =
+ resourceAccess === 'organization' ? organizationSlugs.length : projectRefs.length
+ const scopeText =
+ resourceAccess === 'account'
+ ? 'across your entire account'
+ : boundCount === 0
+ ? `with no ${resourceNoun}s bound`
+ : `across ${boundCount} ${pluralize(boundCount, resourceNoun)}`
+
+ const segments: string[] = []
+ if (readWriteCount > 0) {
+ segments.push(
+ `read-write on ${readWriteCount} ${pluralize(readWriteCount, 'capability', 'capabilities')}`
+ )
+ }
+ if (readCount > 0) {
+ segments.push(
+ segments.length === 0
+ ? `read on ${readCount} ${pluralize(readCount, 'capability', 'capabilities')}`
+ : `read on ${readCount}`
+ )
+ }
+ const sentence = `${segments.join(', ')}, ${scopeText}.`
+
+ return { level, tone, summary: sentence.charAt(0).toUpperCase() + sentence.slice(1) }
+}
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenSummaryRows.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenSummaryRows.tsx
deleted file mode 100644
index 140e38cf8ff..00000000000
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/TokenSummaryRows.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { Badge, cn } from 'ui'
-
-import {
- PERMISSION_MODE_LABEL,
- RISK_DOT_CLASS,
- RISK_TONE_VARIANT,
- type OverallRisk,
- type PermissionCatalogEntry,
- type PermissionMode,
-} from '../AccessToken.permissions'
-import type { EntryAccess } from '../AccessToken.roles'
-import { ExceedsRoleBadge } from './ExceedsRoleBadge'
-
-/**
- * Presentational pieces of the token view sheet's summary section.
- */
-
-interface CapabilityCategoryListProps {
- categories: {
- key: string
- name: string
- entries: { entry: PermissionCatalogEntry; mode: PermissionMode }[]
- }[]
- /** Per-entry access evaluation; entries flagged 'exceeds-role' get the warning pill. */
- accessEntries: Record<string, EntryAccess>
-}
-
-export const CapabilityCategoryList = ({
- categories,
- accessEntries,
-}: CapabilityCategoryListProps) => (
- <div className="space-y-4">
- {categories.map((category) => (
- <div key={category.key} className="space-y-2">
- <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">
- {category.name}
- </p>
- <div className="divide-y">
- {category.entries.map(({ entry, mode }) => {
- const entryAccess = accessEntries[entry.key]
- return (
- <div key={entry.key} className="flex items-center justify-between gap-2 text-sm py-2">
- <span className="flex flex-wrap items-center gap-2">
- <span
- className={cn('h-1.5 w-1.5 shrink-0 rounded-full', RISK_DOT_CLASS[entry.risk])}
- />
- <span className="text-foreground text-wrap">{entry.name}</span>
- {entryAccess?.status === 'exceeds-role' && (
- <ExceedsRoleBadge entry={entry} mode={mode} access={entryAccess} />
- )}
- </span>
- <span className="text-foreground-lighter text-xs font-mono uppercase font-normal text-right">
- {PERMISSION_MODE_LABEL[mode]}
- </span>
- </div>
- )
- })}
- </div>
- </div>
- ))}
- </div>
-)
-
-interface RiskLevelSummaryProps {
- risk: OverallRisk
- /** True when some selected permissions exceed the owner's role, so the risk is role-capped. */
- showRoleCaveat: boolean
-}
-
-export const RiskLevelSummary = ({ risk, showRoleCaveat }: RiskLevelSummaryProps) => (
- <div className="space-y-1">
- <span className="flex flex-wrap items-center gap-2">
- <span className="flex">
- <Badge variant={RISK_TONE_VARIANT[risk.tone]}>{risk.level} Risk</Badge>
- </span>
- <span className="text-sm text-foreground leading-px">
- {risk.text.replace(`${risk.level} — `, '')}
- </span>
- </span>
- {showRoleCaveat && (
- <p className="text-xs text-foreground-lighter">
- Based on what your current role allows this token to do.
- </p>
- )}
- </div>
-)
-
-interface ResourceSummaryItemProps {
- label: string
- /** Mono-rendered identifier under the name — the org slug or project ref. */
- sublabel?: string
- isInaccessible?: boolean
-}
-
-export const ResourceSummaryItem = ({
- label,
- sublabel,
- isInaccessible = false,
-}: ResourceSummaryItemProps) => (
- <div className="flex flex-wrap items-center justify-between gap-2 py-2">
- <span className="flex flex-col gap-0.5">
- <span
- className={cn('text-sm', isInaccessible ? 'text-foreground-lighter' : 'text-foreground')}
- >
- {label}
- </span>
- {sublabel !== undefined && (
- <span className="font-mono text-xs text-foreground-lighter">{sublabel}</span>
- )}
- </span>
- {isInaccessible && <Badge variant="destructive">No longer accessible</Badge>}
- </div>
-)
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.test.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.test.tsx
index 97e970b6c51..3b189eb697d 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.test.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.test.tsx
@@ -1,4 +1,4 @@
-import { screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import { platformComponents as components } from 'api-types'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest'
import {
MOCK_ORG,
+ MOCK_PROJECT,
mockPermissionsApi,
mockScopedTokenEnvironment,
ownerRows,
@@ -68,9 +69,8 @@ describe('ViewTokenSheet', () => {
})
renderSheet()
- // Bound org resolves with its name and slug, meaning evaluation completed without warnings.
+ // Bound org resolves with its name, meaning evaluation completed without warnings.
expect(await screen.findByText(MOCK_ORG.name)).toBeInTheDocument()
- expect(screen.getByText(MOCK_ORG.slug)).toBeInTheDocument()
expect(screen.queryByText('Exceeds your role')).toBeNull()
expect(
screen.queryByText('Some permissions exceed your current role for the selected resources')
@@ -118,7 +118,6 @@ describe('ViewTokenSheet', () => {
).toBeInTheDocument()
// The lost resource renders as an anonymous count, never its slug.
expect(await screen.findByText('1 organization')).toBeInTheDocument()
- expect(await screen.findByText('No longer accessible')).toBeInTheDocument()
expect(screen.queryByText('departed-org')).toBeNull()
expect(screen.queryByText("This token's resources no longer exist")).toBeNull()
})
@@ -140,4 +139,102 @@ describe('ViewTokenSheet', () => {
).toBeGreaterThan(0)
expect(screen.queryByText('This token no longer has access')).toBeNull()
})
+
+ test('renders capability cards with attributed endpoints, MCP tools, and a risk banner', async () => {
+ mockPermissionsApi(ownerRows(MOCK_ORG.slug))
+ mockToken({
+ ...TOKEN_BASE,
+ scope: 'project',
+ project_refs: [MOCK_PROJECT.ref],
+ permissions: ['advisors_read', 'database_read', 'database_write'],
+ })
+ addAPIMock({
+ method: 'get',
+ // @ts-expect-error Studio API is missing from types
+ path: '/scoped-access-token-permissions',
+ response: () =>
+ HttpResponse.json({
+ scopes: {},
+ endpoints: {
+ 'GET /v1/projects/{ref}/advisors/security': [['advisors_read']],
+ 'GET /v1/projects/{ref}/database': [['database_read']],
+ 'POST /v1/projects/{ref}/database/query': [['database_write']],
+ },
+ mcp_tools: {
+ get_advisors: [['advisors_read']],
+ execute_sql: [['database_write']],
+ },
+ }),
+ })
+ renderSheet()
+
+ // Capability cards are closed by default — expand both to see their endpoints and tools.
+ expect(await screen.findByText('Advisors')).toBeInTheDocument()
+ expect(screen.getByText('Database')).toBeInTheDocument()
+ expect(screen.getByText('Read-write')).toBeInTheDocument()
+ expect(screen.getByText('Read')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('Advisors'))
+ fireEvent.click(screen.getByText('Database'))
+
+ // Endpoint rows are copy buttons, so their accessible name carries the method and path.
+ expect(
+ screen.getByRole('button', { name: 'Copy GET /v1/projects/{ref}/advisors/security' })
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'Copy GET /v1/projects/{ref}/database' })
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'Copy POST /v1/projects/{ref}/database/query' })
+ ).toBeInTheDocument()
+ // Every method renders as a badge; non-GET methods get the tinted warning variant.
+ expect(screen.getByText('POST')).toBeInTheDocument()
+
+ expect(screen.getByText('get_advisors')).toBeInTheDocument()
+ expect(screen.getByText('execute_sql')).toBeInTheDocument()
+
+ // project:database is catalog-high risk and granted read-write — max() over capabilities.
+ // "High risk" appears twice: the risk banner title, and Database's own Risk Level badge.
+ expect(screen.getAllByText('High risk').length).toBe(2)
+ expect(
+ screen.getByText('Read-write on 1 capability, read on 1, across 1 project.')
+ ).toBeInTheDocument()
+ })
+
+ test('switches to the dense, filterable view at 9+ granted capabilities', async () => {
+ mockPermissionsApi(ownerRows(MOCK_ORG.slug))
+ mockToken({
+ ...TOKEN_BASE,
+ scope: 'project',
+ project_refs: [MOCK_PROJECT.ref],
+ permissions: [
+ 'advisors_read',
+ 'database_read',
+ 'database_write',
+ 'backups_read',
+ 'custom_domain_read',
+ 'edge_functions_read',
+ 'storage_read',
+ 'realtime_config_read',
+ 'vanity_subdomain_read',
+ 'infra_add_ons_read',
+ ],
+ })
+ renderSheet()
+
+ expect(await screen.findByText('Database')).toBeInTheDocument()
+ expect(screen.getByText(/Not granted · \d+/)).toBeInTheDocument()
+ // All granted capabilities render immediately — no truncation.
+ expect(screen.getByText('Storage')).toBeInTheDocument()
+ expect(screen.getByText('Backups')).toBeInTheDocument()
+
+ // The All/Read/Read-write toggle sits next to the "Capabilities" title, not a text filter.
+ fireEvent.click(screen.getByRole('button', { name: 'Read-write' }))
+ expect(screen.getByText('Database')).toBeInTheDocument()
+ expect(screen.queryByText('Backups')).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Read' }))
+ expect(screen.queryByText('Database')).toBeNull()
+ expect(screen.getByText('Backups')).toBeInTheDocument()
+ })
})
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx
index edb9183e456..8d409f5d0fa 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx
@@ -1,20 +1,27 @@
import dayjs from 'dayjs'
-import { useMemo } from 'react'
+import { useMemo, useState } from 'react'
import { cn, ScrollArea, Sheet, SheetContent, SheetHeader } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { TimestampInfo } from 'ui-patterns/TimestampInfo'
import { TOKEN_DENIED_REMEDIATION } from '../AccessToken.constants'
-import {
- computeOverallRisk,
- PERMISSION_MODE_LABEL,
- scopesToSelection,
- type ResourceAccessMode,
-} from '../AccessToken.permissions'
+import { scopesToSelection, type ResourceAccessMode } from '../AccessToken.permissions'
import { useCapabilitySummary } from '../hooks/useCapabilitySummary'
import { useOrgAndProjectData } from '../hooks/useOrgAndProjectData'
import { useTokenAccessEvaluation } from '../hooks/useTokenAccessEvaluation'
-import { CapabilityCategoryList, ResourceSummaryItem, RiskLevelSummary } from './TokenSummaryRows'
+import {
+ ResourceAccessPills,
+ useResourceAccessWrap,
+ type ResourceAccessPillItem,
+} from './ResourceAccessPills'
+import { CapabilitiesSection } from './TokenCapabilities/CapabilitiesSection'
+import { CapabilityLevelToggle } from './TokenCapabilities/CapabilityLevelToggle'
+import { RiskBanner } from './TokenCapabilities/RiskBanner'
+import {
+ computeRiskBanner,
+ getCapabilityDensityTier,
+ type CapabilityLevelFilter,
+} from './TokenCapabilities/TokenCapabilities.utils'
import { DocsButton } from '@/components/ui/DocsButton'
import { useGetEnabledEndpointsForCapability } from '@/data/scoped-access-tokens/permission-scope-map-query'
import { useScopedAccessTokenQuery } from '@/data/scoped-access-tokens/scoped-access-token-query'
@@ -82,21 +89,27 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
const boundResourcesDeletedText = `Every ${resourceNoun} this token was bound to has been deleted`
const risk = useMemo(
- () => computeOverallRisk(access.effectiveSelection, resourceAccess),
- [access.effectiveSelection, resourceAccess]
+ () =>
+ computeRiskBanner({
+ effectiveSelection: access.effectiveSelection,
+ resourceAccess,
+ organizationSlugs: tokenOrganizationSlugs,
+ projectRefs: tokenProjectRefs,
+ }),
+ [access.effectiveSelection, resourceAccess, tokenOrganizationSlugs, tokenProjectRefs]
)
- const hasCapabilities = grantedScopes.length > 0
-
- const { activeByCategory, mcpTools, capabilityGroups } = useCapabilitySummary({
+ const { capabilities } = useCapabilitySummary({
selection,
grantedScopes,
permissionScopeMap,
})
+ const capabilityTier = getCapabilityDensityTier(capabilities.length)
+ const [levelFilter, setLevelFilter] = useState<CapabilityLevelFilter>('all')
- // Accessible resources render with their name and ref/slug. Resources the user has lost access
- // to are aggregated into an anonymous count — their identifiers aren't shown.
- const resourceSummary = useMemo(() => {
+ // Accessible resources render with their name. Resources the user has lost access to are
+ // aggregated into an anonymous count — their identifiers aren't shown.
+ const resourceItems = useMemo<ResourceAccessPillItem[]>(() => {
const inaccessibleCountItem = (lostCount: number, noun: string) =>
lostCount === 0
? []
@@ -104,7 +117,6 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
{
key: 'inaccessible',
label: `${lostCount} ${pluralize(lostCount, noun)}`,
- sublabel: undefined,
isInaccessible: true,
},
]
@@ -114,42 +126,26 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
const accessible = tokenProjectRefs.flatMap((ref) => {
const name = projectsByRef.get(ref)?.name
if (name === undefined) return []
- return [{ key: ref, label: name, sublabel: ref, isInaccessible: false }]
+ return [{ key: ref, label: name }]
})
- return {
- title: 'Projects',
- items: [
- ...accessible,
- ...inaccessibleCountItem(access.inaccessibleProjectRefs.length, 'project'),
- ],
- }
+ return [
+ ...accessible,
+ ...inaccessibleCountItem(access.inaccessibleProjectRefs.length, 'project'),
+ ]
}
if (resourceAccess === 'organization') {
const organizationsBySlug = new Map(organizations.map((org) => [org.slug, org]))
const accessible = tokenOrganizationSlugs.flatMap((slug) => {
const name = organizationsBySlug.get(slug)?.name
if (name === undefined) return []
- return [{ key: slug, label: name, sublabel: slug, isInaccessible: false }]
+ return [{ key: slug, label: name }]
})
- return {
- title: 'Organizations',
- items: [
- ...accessible,
- ...inaccessibleCountItem(access.inaccessibleOrgSlugs.length, 'organization'),
- ],
- }
- }
- return {
- title: 'Account',
- items: [
- {
- key: 'account',
- label: 'Account-level access',
- sublabel: undefined,
- isInaccessible: false,
- },
- ],
+ return [
+ ...accessible,
+ ...inaccessibleCountItem(access.inaccessibleOrgSlugs.length, 'organization'),
+ ]
}
+ return [{ key: 'account', label: 'Account-level access' }]
}, [
resourceAccess,
tokenProjectRefs,
@@ -160,82 +156,7 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
access.inaccessibleOrgSlugs,
])
- const rows: [string, React.ReactNode][] = token
- ? [
- [
- 'Created',
- token.created_at ? (
- <TimestampInfo
- utcTimestamp={token.created_at}
- label={dayjs(token.created_at).format('DD MMM YYYY')}
- className="text-sm"
- />
- ) : (
- <span className="text-foreground-lighter">Unknown</span>
- ),
- ],
- [
- 'Last used',
- token.last_used_at ? (
- <TimestampInfo
- utcTimestamp={token.last_used_at}
- label={dayjs(token.last_used_at).fromNow()}
- className="text-sm"
- />
- ) : (
- <span className="text-foreground-lighter">Never</span>
- ),
- ],
- [
- 'Expires',
- token.expires_at ? (
- <TimestampInfo
- utcTimestamp={token.expires_at}
- label={dayjs(token.expires_at).format('DD MMM YYYY')}
- className="text-sm"
- />
- ) : (
- <span className="text-foreground-lighter">Never</span>
- ),
- ],
- [
- 'Resource access',
- <div key="resource-access" className="space-y-2">
- <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">
- {resourceSummary.title}
- </p>
- <div className="divide-y">
- {resourceSummary.items.length === 0 && hasNoBoundResources && (
- <p className="py-2 text-sm text-foreground-lighter">{boundResourcesDeletedText}</p>
- )}
- {resourceSummary.items.length === 0 && !hasNoBoundResources && (
- <p className="py-2 text-sm text-foreground-lighter">-</p>
- )}
- {resourceSummary.items.map((item) => (
- <ResourceSummaryItem
- key={item.key}
- label={item.label}
- sublabel={item.sublabel}
- isInaccessible={item.isInaccessible}
- />
- ))}
- </div>
- </div>,
- ],
- [
- 'Capabilities',
- hasCapabilities ? (
- <CapabilityCategoryList categories={activeByCategory} accessEntries={access.entries} />
- ) : (
- <span className="text-foreground-lighter">No capabilities selected</span>
- ),
- ],
- [
- 'Risk level',
- <RiskLevelSummary key="risk" risk={risk} showRoleCaveat={hasExceedingCapabilities} />,
- ],
- ]
- : []
+ const { containerRef: pillsRef, isWrapped: isResourceAccessWrapped } = useResourceAccessWrap()
return (
<Sheet open={visible} onOpenChange={() => onClose()}>
@@ -244,7 +165,11 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
size="default"
className="flex h-full flex-col gap-0 sm:w-[656px] lg:w-[800px]"
>
- <SheetHeader className={cn('flex flex-row justify-between gap-x-4 items-center border-b')}>
+ <SheetHeader
+ className={cn(
+ 'flex flex-col md:flex-row justify-between gap-4 items-start md:items-center border-b'
+ )}
+ >
<p className="truncate" title={`View access for ${token?.name}`}>
View access for {token?.name}
</p>
@@ -261,7 +186,10 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
/>
</div>
</SheetHeader>
- <ScrollArea className="flex-1">
+ {/* Radix wraps viewport children in an inline-styled display:table div that grows to fit
+ the widest child, which would let one long endpoint path expand the sheet instead of
+ clipping — force it back to block so widths are bounded and rows can truncate. */}
+ <ScrollArea className="flex-1 [&>[data-radix-scroll-area-viewport]>div]:block!">
<div className="space-y-6 px-5 sm:px-6 py-6">
{isTokenLoading && (
<div className="flex items-center justify-center py-8">
@@ -300,74 +228,93 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
description="A token only works with permissions you currently hold. Permissions marked below will be denied until your role includes them."
/>
)}
+
<div className="flex flex-col gap-3">
- <h3 className="text-sm">Token summary</h3>
- <dl className="divide-y rounded-md border bg-surface-300">
- {rows.map(([key, value]) => (
- <div key={key} className="grid grid-cols-3 gap-4 px-4 py-3">
- <dt className="text-sm text-foreground-lighter">{key}</dt>
- <dd className="col-span-2 text-sm text-foreground">{value}</dd>
- </div>
- ))}
- </dl>
+ <h3 className="text-sm">Risk assessment</h3>
+ <RiskBanner risk={risk} showRoleCaveat={hasExceedingCapabilities} />
</div>
- {hasCapabilities && (
- <>
- <div className="flex flex-col gap-3">
- <h3 className="text-sm">Management API endpoints enabled</h3>
- {capabilityGroups.length === 0 ? (
- <p className="text-xs text-foreground-light">
- No Management API endpoints are enabled by the selected capabilities.
- </p>
- ) : (
- capabilityGroups.map(({ entry, mode, endpoints }) => (
- <div key={entry.key} className="rounded-md border">
- <div className="flex items-center justify-between border-b bg-surface-100 px-3 py-2">
- <span className="text-xs text-foreground">{entry.name}</span>
- <span className="text-[11px] font-mono uppercase text-foreground-lighter">
- {PERMISSION_MODE_LABEL[mode]}
- </span>
- </div>
- <div className="divide-y">
- {endpoints.map(([method, path]) => (
- <div
- key={`${method} ${path}`}
- className="flex items-center gap-2 px-3 py-1.5 font-mono text-xs"
- >
- <span className="w-14 shrink-0 text-foreground-light">
- {method}
- </span>
- <span className="text-foreground">{path}</span>
- </div>
- ))}
- </div>
- </div>
- ))
- )}
+ <div className="flex flex-col gap-3">
+ <h3 className="text-sm">Token summary</h3>
+ <dl className="divide-y rounded-md border bg-surface-300">
+ <div className="flex items-center justify-between gap-4 px-4 py-3">
+ <dt className="shrink-0 text-sm text-foreground-lighter">Created</dt>
+ <dd className="text-sm text-foreground">
+ {token.created_at ? (
+ <TimestampInfo
+ utcTimestamp={token.created_at}
+ label={dayjs(token.created_at).fromNow()}
+ className="text-sm"
+ />
+ ) : (
+ <span className="text-foreground-lighter">Unknown</span>
+ )}
+ </dd>
</div>
-
- <div className="flex flex-col gap-3">
- <h3 className="text-sm">MCP tools</h3>
- {mcpTools.length === 0 ? (
- <p className="text-xs text-foreground-light">
- No MCP tools are enabled by the selected capabilities.
- </p>
- ) : (
- <div className="flex flex-wrap gap-2">
- {mcpTools.map((tool) => (
- <span
- key={tool}
- className="rounded border bg-surface-100 px-2 py-1 font-mono text-xs text-foreground-light"
- >
- {tool}
- </span>
- ))}
- </div>
+ <div className="flex items-center justify-between gap-4 px-4 py-3">
+ <dt className="shrink-0 text-sm text-foreground-lighter">Last used</dt>
+ <dd className="text-sm text-foreground">
+ {token.last_used_at ? (
+ <TimestampInfo
+ utcTimestamp={token.last_used_at}
+ label={dayjs(token.last_used_at).fromNow()}
+ className="text-sm"
+ />
+ ) : (
+ <span className="text-foreground-lighter">Never</span>
+ )}
+ </dd>
+ </div>
+ <div className="flex items-center justify-between gap-4 px-4 py-3">
+ <dt className="shrink-0 text-sm text-foreground-lighter">Expires</dt>
+ <dd className="text-sm text-foreground">
+ {token.expires_at ? (
+ <TimestampInfo
+ utcTimestamp={token.expires_at}
+ label={dayjs(token.expires_at).fromNow()}
+ className="text-sm"
+ />
+ ) : (
+ <span className="text-foreground-lighter">Never</span>
+ )}
+ </dd>
+ </div>
+ <div
+ className={cn(
+ 'flex flex-col items-start justify-between gap-4 px-4 py-3 sm:flex-row',
+ isResourceAccessWrapped ? 'sm:items-start' : 'sm:items-center'
)}
+ >
+ <dt className="shrink-0 text-sm text-foreground-lighter">Resource access</dt>
+ <dd className="w-full min-w-0 text-sm text-foreground sm:w-auto sm:flex-1">
+ <div
+ ref={pillsRef}
+ className="flex flex-wrap justify-start gap-1.5 sm:justify-end"
+ >
+ <ResourceAccessPills
+ resourceAccess={resourceAccess}
+ items={resourceItems}
+ emptyText={hasNoBoundResources ? boundResourcesDeletedText : '-'}
+ />
+ </div>
+ </dd>
</div>
- </>
- )}
+ </dl>
+ </div>
+
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm">Capabilities</h3>
+ {capabilityTier === 'dense' && (
+ <CapabilityLevelToggle value={levelFilter} onChange={setLevelFilter} />
+ )}
+ </div>
+ <CapabilitiesSection
+ capabilities={capabilities}
+ accessEntries={access.entries}
+ levelFilter={levelFilter}
+ />
+ </div>
</>
)}
</div>
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/hooks/useCapabilitySummary.ts b/apps/studio/components/interfaces/Account/AccessTokens/hooks/useCapabilitySummary.ts
index 76b78959d4a..891a56cc2ef 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/hooks/useCapabilitySummary.ts
+++ b/apps/studio/components/interfaces/Account/AccessTokens/hooks/useCapabilitySummary.ts
@@ -2,15 +2,16 @@ import { useMemo } from 'react'
import {
getEntryScopes,
- PERMISSION_CATALOG_BY_CATEGORY,
+ PERMISSION_CATALOG,
type PermissionCatalogEntry,
type PermissionMode,
type PermissionSelection,
} from '../AccessToken.permissions'
import {
getEnabledEndpointsForCapability,
- getEnabledMcpTools,
- PermissionScopeMap,
+ getEnabledMcpToolsForCapability,
+ type EnabledEndpoint,
+ type PermissionScopeMap,
} from '@/data/scoped-access-tokens/permission-scope-map-query'
interface UseCapabilitySummaryArgs {
@@ -19,49 +20,43 @@ interface UseCapabilitySummaryArgs {
permissionScopeMap: PermissionScopeMap | undefined
}
+export interface CapabilitySummaryEntry {
+ entry: PermissionCatalogEntry
+ mode: PermissionMode
+ endpoints: EnabledEndpoint[]
+ mcpTools: string[]
+}
+
/**
- * Selection-derived summary data for the token view sheet: selected entries grouped by catalog
- * category, the Management API endpoints each capability enables, and the enabled MCP tools.
+ * Selection-derived summary data for the token view sheet: every granted catalog entry paired with
+ * the Management API endpoints and MCP tools it enables.
*/
export const useCapabilitySummary = ({
selection,
grantedScopes,
permissionScopeMap,
}: UseCapabilitySummaryArgs) => {
- const activeByCategory = useMemo(
- () =>
- PERMISSION_CATALOG_BY_CATEGORY.map((category) => ({
- ...category,
- entries: category.entries
- .map((entry) => ({ entry, mode: selection[entry.key] ?? 'none' }))
- .filter(({ mode }) => mode !== 'none'),
- })).filter((category) => category.entries.length > 0),
- [selection]
- )
-
- const mcpTools = useMemo(
- () => getEnabledMcpTools({ grantedScopes, permissionScopeMap }),
- [grantedScopes, permissionScopeMap]
- )
+ const capabilities = useMemo(() => {
+ const result: CapabilitySummaryEntry[] = []
+ for (const entry of PERMISSION_CATALOG) {
+ const mode = selection[entry.key] ?? 'none'
+ if (mode === 'none') continue
- const capabilityGroups = useMemo(() => {
- const groups: { entry: PermissionCatalogEntry; mode: PermissionMode; endpoints: string[][] }[] =
- []
- for (const category of activeByCategory) {
- for (const { entry, mode } of category.entries) {
- const capabilityScopes = getEntryScopes(entry, mode)
- const endpoints = getEnabledEndpointsForCapability({
- capabilityScopes,
- allGrantedScopes: grantedScopes,
- permissionScopeMap,
- })
- if (endpoints.length > 0) {
- groups.push({ entry, mode, endpoints: endpoints.map((e) => [e.method, e.path]) })
- }
- }
+ const capabilityScopes = getEntryScopes(entry, mode)
+ const endpoints = getEnabledEndpointsForCapability({
+ capabilityScopes,
+ allGrantedScopes: grantedScopes,
+ permissionScopeMap,
+ })
+ const mcpTools = getEnabledMcpToolsForCapability({
+ capabilityScopes,
+ allGrantedScopes: grantedScopes,
+ permissionScopeMap,
+ })
+ result.push({ entry, mode, endpoints, mcpTools })
}
- return groups
- }, [activeByCategory, grantedScopes, permissionScopeMap])
+ return result
+ }, [selection, grantedScopes, permissionScopeMap])
- return { activeByCategory, mcpTools, capabilityGroups }
+ return { capabilities }
}
diff --git a/apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts b/apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
index 604cc8d68eb..c662c8f3667 100644
--- a/apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
+++ b/apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
@@ -154,6 +154,34 @@ export const getEnabledEndpointsForCapability = ({
.map(([raw]) => splitEndpoint(raw))
}
+/**
+ * MCP-tool counterpart to getEnabledEndpointsForCapability: the MCP tools enabled by the complete
+ * granted-scope set that owe that to `capabilityScopes`, for grouping enabled tools under the
+ * capability that contributes them.
+ */
+export const getEnabledMcpToolsForCapability = ({
+ capabilityScopes,
+ allGrantedScopes,
+ permissionScopeMap,
+}: {
+ capabilityScopes: Iterable<string>
+ allGrantedScopes: Iterable<string>
+ permissionScopeMap: PermissionScopeMap | undefined
+}): string[] => {
+ if (permissionScopeMap == null) return []
+
+ const granted = new Set(allGrantedScopes)
+ const capability = new Set(capabilityScopes)
+ return Object.entries(permissionScopeMap.mcp_tools)
+ .filter(([, groups]) =>
+ groups.some(
+ (group) =>
+ group.some((scope) => capability.has(scope)) && group.every((scope) => granted.has(scope))
+ )
+ )
+ .map(([tool]) => tool)
+}
+
/**
* Informational lookup for the per-permission risk tooltip: the MCP tools associated with any of
* the given scopes. Unlike getEnabledMcpTools this is not conjunctive — it surfaces every tool that