Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

12.4 KB
Raw Blame
'use client'
import type { FC } from 'react'
import type { ToolWithProvider } from '../../../workflow/types'
import {
  AlertDialog,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import copy from 'copy-to-clipboard'
import * as React from 'react'
import { useCallback, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import Icon from '@/app/components/plugins/card/base/card-icon'
import { useCanManageMCP } from '@/app/components/tools/hooks/use-tool-permissions'
import { openOAuthPopup } from '@/hooks/use-oauth'
import { consoleQuery } from '@/service/console'
import { selectToolProviderTools } from '../../utils/query-select'
import ListLoading from './list-loading'
import OperationMenu from './operation-menu'
import ToolItem from './tool-item'

type Props = Readonly<{
  detail: ToolWithProvider
  onUpdate: () => void
  onEdit: (providerID: string) => void
  onDelete: (providerID: string) => void
  onHide: () => void
  isTriggerAuthorize: boolean
  onFirstCreate: () => void
}>

const MCPDetailContent: FC<Props> = ({
  detail,
  onUpdate,
  onEdit,
  onDelete,
  onHide,
  isTriggerAuthorize,
  onFirstCreate,
}) => {
  const { t } = useTranslation(['common', 'tools'])
  const canManageMCP = useCanManageMCP()

  const queryClient = useQueryClient()
  const { data, isFetching: isGettingTools } = useQuery(
    consoleQuery.workspaces.current.toolProvider.mcp.tools.byProviderId.get.queryOptions({
      input: { params: { provider_id: detail.id } },
      enabled: !!detail.is_team_authorization && !!detail.id,
      select: selectToolProviderTools,
    }),
  )
  const { mutateAsync: updateTools, isPending: isUpdating } = useMutation(
    consoleQuery.workspaces.current.toolProvider.mcp.update.byProviderId.get.mutationOptions(),
  )
  const { mutateAsync: authorizeMcp, isPending: isAuthorizing } = useMutation(
    consoleQuery.workspaces.current.toolProvider.mcp.auth.post.mutationOptions(),
  )
  const toolList = data?.tools || []

  const [isShowUpdateConfirm, { setTrue: showUpdateConfirm, setFalse: hideUpdateConfirm }] =
    useBoolean(false)

  const handleUpdateTools = useCallback(async () => {
    hideUpdateConfirm()
    if (!canManageMCP || !detail) return
    await updateTools({ params: { provider_id: detail.id } })
    queryClient.invalidateQueries({
      queryKey: consoleQuery.workspaces.current.toolProvider.mcp.tools.byProviderId.get.queryKey({
        input: { params: { provider_id: detail.id } },
      }),
    })
    queryClient.invalidateQueries({
      queryKey: consoleQuery.workspaces.current.tools.mcp.get.queryKey(),
    })
    onUpdate()
  }, [canManageMCP, detail, hideUpdateConfirm, onUpdate, queryClient, updateTools])

  const hasTriggeredAuthorizeRef = useRef(false)

  const handleOAuthCallback = useCallback(() => {
    if (!canManageMCP) return
    if (!detail.id) return
    handleUpdateTools()
  }, [canManageMCP, detail.id, handleUpdateTools])

  const handleAuthorize = useCallback(async () => {
    if (!canManageMCP) return
    onFirstCreate()
    if (!detail) return
    try {
      const res = await authorizeMcp({ body: { provider_id: detail.id } })
      if (res.result === 'success') handleUpdateTools()
      else if (res.authorization_url) openOAuthPopup(res.authorization_url, handleOAuthCallback)
    } catch {
      // On authorization error, refresh the parent component state
      // to update the connection status indicator
      onUpdate()
    }
  }, [
    canManageMCP,
    onFirstCreate,
    detail,
    authorizeMcp,
    handleUpdateTools,
    handleOAuthCallback,
    onUpdate,
  ])

  useEffect(() => {
    if (!isTriggerAuthorize || hasTriggeredAuthorizeRef.current) return

    hasTriggeredAuthorizeRef.current = true
    handleAuthorize()
  }, [handleAuthorize, isTriggerAuthorize])

  if (!detail) return null
  const identifierLabel = t(($) => $['mcp.identifier'], { ns: 'tools' })
  const serverUrlLabel = t(($) => $['mcp.modal.serverUrl'], { ns: 'tools' })

  return (
    <>
      <div
        className={cn('shrink-0 border-b border-divider-subtle bg-components-panel-bg p-4 pb-3')}
      >
        <div className="flex">
          <div className="shrink-0 overflow-hidden rounded-xl border border-components-panel-border-subtle">
            <Icon src={detail.icon} />
          </div>
          <div className="ms-3 w-0 grow">
            <div className="flex h-5 items-center">
              <div className="truncate system-md-semibold text-text-primary">{detail.name}</div>
            </div>
            <div className="mt-0.5 flex items-center gap-1">
              <Tooltip>
                <TooltipTrigger
                  render={
                    <Button
                      type="button"
                      variant="ghost"
                      size="small"
                      className="h-auto shrink-0 cursor-pointer rounded bg-transparent p-0 text-start system-xs-regular text-text-secondary hover:bg-transparent"
                      onClick={() => copy(detail.server_identifier || '')}
                    >
                      {detail.server_identifier}
                      <span className="sr-only"> {identifierLabel}</span>
                    </Button>
                  }
                />
                <TooltipContent>{identifierLabel}</TooltipContent>
              </Tooltip>
              <div className="shrink-0 system-xs-regular text-text-quaternary">·</div>
              <Tooltip>
                <TooltipTrigger
                  render={
                    <div className="truncate system-xs-regular text-text-secondary">
                      <span className="sr-only">{`${serverUrlLabel}: `}</span>
                      {detail.server_url}
                    </div>
                  }
                />
                <TooltipContent>{serverUrlLabel}</TooltipContent>
              </Tooltip>
            </div>
          </div>
          <div className="flex gap-1">
            {canManageMCP && (
              <OperationMenu
                onEdit={() => onEdit(detail.id)}
                onRemove={() => onDelete(detail.id)}
              />
            )}
            <IconButton
              aria-label={t(($) => $['operation.close'], { ns: 'common' })}
              onClick={onHide}
            >
              <span aria-hidden className="i-ri-close-line size-4" />
            </IconButton>
          </div>
        </div>
        <div className="mt-5">
          {!isAuthorizing && detail.is_team_authorization && (
            <Button
              variant="secondary"
              className="w-full"
              onClick={handleAuthorize}
              disabled={!canManageMCP}
            >
              <StatusDot status="success" />
              {t(($) => $['auth.authorized'], { ns: 'tools' })}
            </Button>
          )}
          {!detail.is_team_authorization && !isAuthorizing && (
            <Button
              variant="primary"
              className="w-full"
              onClick={handleAuthorize}
              disabled={!canManageMCP}
            >
              {t(($) => $['mcp.authorize'], { ns: 'tools' })}
            </Button>
          )}
          {isAuthorizing && (
            <Button variant="primary" className="w-full" disabled>
              <span aria-hidden className="i-ri-loader-2-line size-4 animate-spin" />
              {t(($) => $['mcp.authorizing'], { ns: 'tools' })}
            </Button>
          )}
        </div>
      </div>
      <div className="flex grow flex-col">
        {((detail.is_team_authorization && isGettingTools) || isUpdating) && (
          <>
            <div className="flex shrink-0 justify-between gap-2 px-4 pt-2 pb-1">
              <div className="flex h-6 items-center">
                {!isUpdating && (
                  <div className="system-sm-semibold-uppercase text-text-secondary">
                    {t(($) => $['mcp.gettingTools'], { ns: 'tools' })}
                  </div>
                )}
                {isUpdating && (
                  <div className="system-sm-semibold-uppercase text-text-secondary">
                    {t(($) => $['mcp.updateTools'], { ns: 'tools' })}
                  </div>
                )}
              </div>
              <div></div>
            </div>
            <div className="flex size-full grow flex-col overflow-hidden px-4 pb-4">
              <ListLoading />
            </div>
          </>
        )}
        {!isUpdating && detail.is_team_authorization && !isGettingTools && !toolList.length && (
          <div className="flex size-full flex-col items-center justify-center">
            <div className="mb-3 system-sm-regular text-text-tertiary">
              {t(($) => $['mcp.toolsEmpty'], { ns: 'tools' })}
            </div>
            <Button variant="primary" onClick={handleUpdateTools} disabled={!canManageMCP}>
              {t(($) => $['mcp.getTools'], { ns: 'tools' })}
            </Button>
          </div>
        )}
        {!isUpdating && !isGettingTools && toolList.length > 0 && (
          <>
            <div className="flex shrink-0 justify-between gap-2 px-4 pt-2 pb-1">
              <div className="flex h-6 items-center">
                {toolList.length > 1 && (
                  <div className="system-sm-semibold-uppercase text-text-secondary">
                    {t(($) => $['mcp.toolsNum'], { ns: 'tools', count: toolList.length })}
                  </div>
                )}
                {toolList.length === 1 && (
                  <div className="system-sm-semibold-uppercase text-text-secondary">
                    {t(($) => $['mcp.onlyTool'], { ns: 'tools' })}
                  </div>
                )}
              </div>
              <div>
                <Button size="small" onClick={showUpdateConfirm} disabled={!canManageMCP}>
                  <span aria-hidden className="i-ri-loop-left-line size-3.5" />
                  {t(($) => $['mcp.update'], { ns: 'tools' })}
                </Button>
              </div>
            </div>
            <div className="flex h-0 w-full grow flex-col gap-2 overflow-y-auto px-4 pb-4">
              {toolList.map((tool) => (
                <ToolItem key={`${detail.id}${tool.name}`} tool={tool} />
              ))}
            </div>
          </>
        )}

        {!isUpdating && !detail.is_team_authorization && (
          <div className="flex size-full flex-col items-center justify-center">
            {!isAuthorizing && (
              <div className="mb-1 system-md-medium text-text-secondary">
                {t(($) => $['mcp.authorizingRequired'], { ns: 'tools' })}
              </div>
            )}
            {isAuthorizing && (
              <div className="mb-1 system-md-medium text-text-secondary">
                {t(($) => $['mcp.authorizing'], { ns: 'tools' })}
              </div>
            )}
            <div className="system-sm-regular text-text-tertiary">
              {t(($) => $['mcp.authorizeTip'], { ns: 'tools' })}
            </div>
          </div>
        )}
      </div>
      <AlertDialog
        open={canManageMCP && isShowUpdateConfirm}
        onOpenChange={(open) => !open && hideUpdateConfirm()}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t(($) => $['mcp.toolUpdateConfirmTitle'], { ns: 'tools' })}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(($) => $['mcp.toolUpdateConfirmContent'], { ns: 'tools' })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancelButton>
              {t(($) => $['operation.cancel'], { ns: 'common' })}
            </AlertDialogCancelButton>
            <AlertDialogConfirmButton tone="default" onClick={handleUpdateTools}>
              {t(($) => $['operation.confirm'], { ns: 'common' })}
            </AlertDialogConfirmButton>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

export default MCPDetailContent