본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

채팅 - 도구 승인

원문 보기 위키 갱신

채팅 - 도구 승인 (Tool Approval)

에이전트 도구 호출이 실행되기 전에 사람이 검토하고 승인 또는 거부할 수 있는 human-in-the-loop 체크포인트를 추가할 수 있어요.

출처: MUI X documentation

본문

도구 승인(tool approval)을 사용하면 에이전트가 잠재적으로 위험한 액션을 요청할 때 일시 중지하고, 사용자에게 승인/거부 인터페이스를 제공하며, 사용자의 결정에 따라 도구 실행을 재개하거나 취소할 수 있어요.

승인 워크플로 (Approval workflow)

승인 수명주기는 표준 도구 호출 상태를 두 단계로 확장합니다.

상태 (State) 설명 (Description)
input-streaming 도구 입력 JSON이 스트리밍되는 중
input-available 도구 입력이 완전히 준비됨
approval-requested 스트림이 일시 중지되고 사용자 승인이 필요함
approval-responded 사용자가 응답했고 스트림이 계속됨
output-available 도구 출력이 준비됨(승인된 경우)
output-denied 사용자가 도구 호출을 거부함

스트림은 approval-requested에서 일시 중지되어, UI가 addToolApprovalResponse()를 호출할 때까지 기다립니다.

작업 중인 도구 호출 승인 (Approving a tool call in action)

제안된 프롬프트를 보내보세요. 스트림은 approval-requested에서 일시 중지되어 호출을 승인하거나 거부할 때까지 기다립니다.

'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import type {
  ChatAdapter,
  ChatMessage,
  ChatRealtimeEvent,
} from '@mui/x-chat/headless';
import { demoUsers } from 'docs/data/chat/core/examples/shared/demoData';
import { createChunkStream } from 'docs/data/chat/core/examples/shared/demoUtils';

const CONVERSATION_ID = 'tool-approval';

function createToolApprovalAdapter(): ChatAdapter {
  let onEventRef: ((event: ChatRealtimeEvent) => void) | null = null;
  let pendingMessage: ChatMessage | null = null;

  return {
    async sendMessage() {
      const messageId = 'assistant-approval';
      const textId = 'assistant-approval-text';
      const toolCallId = 'cleanup-1';

      pendingMessage = {
        id: messageId,
        conversationId: CONVERSATION_ID,
        role: 'assistant',
        author: demoUsers.agent,
        status: 'sent',
        parts: [
          {
            type: 'text',
            text: 'I need approval before deleting these files.',
          },
          {
            type: 'dynamic-tool',
            toolInvocation: {
              toolCallId,
              toolName: 'delete_files',
              state: 'approval-requested',
              input: { path: '/tmp/cache', recursive: true },
              approvalId: 'approval-1',
            },
          },
        ],
      };

      return createChunkStream(
        [
          { type: 'start', messageId, author: demoUsers.agent },
          { type: 'text-start', id: textId },
          {
            type: 'text-delta',
            id: textId,
            delta: 'I need approval before deleting these files.',
          },
          { type: 'text-end', id: textId },
          {
            type: 'tool-approval-request',
            toolCallId,
            toolName: 'delete_files',
            input: { path: '/tmp/cache', recursive: true },
            // The optional approval id is round-tripped: the built-in widget
            // responds with it, and the controller matches the invocation by it.
            approvalId: 'approval-1',
            dynamic: true,
          },
          { type: 'finish', messageId, finishReason: 'tool-call' },
        ],
        { delayMs: 240 },
      );
    },
    subscribe({ onEvent }) {
      onEventRef = onEvent;
      return () => {
        onEventRef = null;
      };
    },
    async addToolApprovalResponse({ approved, reason }) {
      if (!pendingMessage) {
        return;
      }

      // 1. Move the tool invocation to its terminal state.
      onEventRef?.({
        type: 'message-updated',
        message: {
          ...pendingMessage,
          parts: [
            pendingMessage.parts[0],
            {
              type: 'dynamic-tool',
              toolInvocation: {
                toolCallId: 'cleanup-1',
                toolName: 'delete_files',
                state: approved ? 'output-available' : 'output-denied',
                input: { path: '/tmp/cache', recursive: true },
                approvalId: 'approval-1',
                approval: { approved, reason },
                output: approved ? { deleted: 3 } : undefined,
              },
            },
          ],
        },
      });

      // 2. Emit a follow-up assistant message after a short delay.
      setTimeout(() => {
        onEventRef?.({
          type: 'message-added',
          message: {
            id: 'assistant-followup',
            conversationId: CONVERSATION_ID,
            role: 'assistant',
            author: demoUsers.agent,
            status: 'sent',
            parts: [
              {
                type: 'text',
                text: approved
                  ? 'Deleted 3 files.'
                  : "Okay, I won't delete anything.",
              },
            ],
          },
        });
      }, 400);
    },
  };
}

export default function ToolApprovalFlow() {
  const adapter = React.useMemo(() => createToolApprovalAdapter(), []);

  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={CONVERSATION_ID}
      suggestions={['Clean up /tmp/cache']}
      suggestionsAutoSubmit
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

승인 요청 트리거 (Triggering an approval request)

백엔드가 도구 호출에 사용자 승인이 필요하다고 판단하면 tool-approval-request chunk를 보냅니다(서버 측은 Building an adapter 참고).

controller.enqueue({
  type: 'tool-approval-request',
  toolCallId: 'call-1',
  toolName: 'delete_files',
  input: { path: '/tmp/data', recursive: true },
  approvalId: 'approval-1', // optional, defaults to toolCallId
});
필드 (Field) 타입 (Type) 설명 (Description)
toolCallId string 게이트가 적용되는 도구 호출
toolName string 승인을 요청하는 도구의 이름
input ChatToolInput<TToolName> 도구의 입력(도구별로 타입이 지정되며, dynamic 도구는 unknown), 사용자에게 표시됨
approvalId string | undefined 선택적인 별도의 승인 ID. 호출에 toolInvocation.approvalId로 저장됨. 존재하면 이 값으로, 없으면 toolCallId로 응답.
dynamic true | undefined dynamic(미등록) 도구를 게이트할 때 true로 설정. dynamic-tool 승인 chunk에는 필수.

이 chunk가 도착하면 도구 호출은 state: 'approval-requested'로 이동합니다.

승인 응답 구현 (Implementing approval responses)

어댑터에 addToolApprovalResponse를 구현해 사용자의 결정을 백엔드로 보내세요.

interface ChatAddToolApproveResponseInput {
  id: string; // the chunk's approvalId when provided, otherwise the toolCallId
  approved: boolean; // true = approved, false = denied
  reason?: string; // optional reason surfaced to the model when denied
}
async addToolApprovalResponse({ id, approved, reason }) {
  await fetch('/api/tool-approval', {
    method: 'POST',
    body: JSON.stringify({ id, approved, reason }),
  });
},

짚고 넘어갈 동작이 두 가지 있어요.

  • reason은 호출에 toolInvocation.approval.reason으로 저장되며, 호출이 output-denied로 끝나면 내장 도구 위젯이 표시합니다. 그 외에는 백엔드로만 전송됩니다. 내장 Deny 버튼은 reason을 보내지 않아요. reason을 수집하려면 커스텀 렌더러를 제공해야 합니다(아래 Registering custom renderers for tool approval 참고).
  • 어댑터의 addToolApprovalResponse가 reject되면 내장 위젯이 버튼을 다시 활성화하고, 오류는 채팅 오류 채널(onError)로 보고됩니다. 호출은 approval-requested에 남아 있어 사용자가 다시 시도할 수 있어요.

UI에서 승인 요청에 응답하기 (Responding to approval requests in the UI)

useChat()을 사용해 컴포넌트에서 addToolApprovalResponse를 호출하세요.

const { addToolApprovalResponse } = useChat();

// Approve
await addToolApprovalResponse({
  id: toolCall.approvalId ?? toolCall.toolCallId,
  approved: true,
});

// Deny with reason
await addToolApprovalResponse({
  id: toolCall.approvalId ?? toolCall.toolCallId,
  approved: false,
  reason: 'User declined the operation',
});

응답 후 도구 호출은 state: 'approval-responded'로 이동하고 스트림이 계속됩니다. 승인되면 도구는 실행을 진행해 결국 output-available에 도달하고, 거부되면 output-denied로 이동해요.

사용자에게 확인 요청하기 (Prompting the user for confirmation)

ChatConfirmation은 메시지와 두 개의 액션 버튼이 있는 눈에 띄는 경고 카드를 렌더링해 human-in-the-loop 체크포인트를 제공합니다.

import { ChatConfirmation } from '@mui/x-chat';

<ChatConfirmation
  message="Are you sure you want to delete all files?"
  onConfirm={() => agent.confirm()}
  onCancel={() => agent.cancel()}
/>;

인터랙티브 플레이그라운드 (Interactive playground)

다양한 상태에서 ChatConfirmation UI를 미리 볼 수 있어요.

import * as React from 'react';
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Snackbar from '@mui/material/Snackbar';
import { ChatConfirmation } from '@mui/x-chat';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import {
  DividerLabel,
  TextControl,
} from 'docs/src/modules/components/chat-playground/controls';
import {
  useCustomizations,
  type CustomizationDef,
} from 'docs/src/modules/components/chat-playground/useCustomizations';

type ClassKey =
  'root' | 'icon' | 'message' | 'actions' | 'confirmButton' | 'cancelButton';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  { name: 'root', description: 'The confirmation card.' },
  {
    name: 'icon',
    selector: '.MuiChatConfirmation-icon',
    description: 'The warning icon container.',
  },
  {
    name: 'message',
    selector: '.MuiChatConfirmation-message',
    description: 'The message paragraph.',
  },
  {
    name: 'actions',
    selector: '.MuiChatConfirmation-actions',
    description: 'The button row.',
  },
  {
    name: 'confirmButton',
    selector: '.MuiChatConfirmation-confirmButton',
    description: 'The primary confirm button.',
  },
  {
    name: 'cancelButton',
    selector: '.MuiChatConfirmation-cancelButton',
    description: 'The cancel button.',
  },
];

export default function ChatConfirmationPlayground() {
  const [message, setMessage] = React.useState(
    'The assistant wants to delete 3 files. Approve this action?',
  );
  const [confirmLabel, setConfirmLabel] = React.useState('Allow');
  const [cancelLabel, setCancelLabel] = React.useState('Deny');
  const [resolution, setResolution] = React.useState<'confirm' | 'cancel' | null>(
    null,
  );
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);

  const cardSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatConfirmation"
      description="A confirmation card for gating a tool call before it runs."
      previewMinHeight={220}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>props</DividerLabel>
          <TextControl
            label="message"
            value={message}
            onChange={setMessage}
            multiline
            rows={2}
          />
          <TextControl
            label="confirmLabel"
            value={confirmLabel}
            onChange={setConfirmLabel}
          />
          <TextControl
            label="cancelLabel"
            value={cancelLabel}
            onChange={setCancelLabel}
          />
        </React.Fragment>
      }
      preview={
        <Box sx={{ width: '100%' }}>
          <ChatConfirmation
            message={message}
            confirmLabel={confirmLabel}
            cancelLabel={cancelLabel}
            onConfirm={() => setResolution('confirm')}
            onCancel={() => setResolution('cancel')}
            sx={cardSx}
          />
          <Snackbar
            open={resolution !== null}
            autoHideDuration={1600}
            anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            onClose={() => setResolution(null)}
          >
            <Alert
              severity={resolution === 'confirm' ? 'success' : 'warning'}
              variant="filled"
              onClose={() => setResolution(null)}
            >
              {resolution === 'confirm' ? 'onConfirm fired' : 'onCancel fired'}
            </Alert>
          </Snackbar>
        </Box>
      }
    />
  );
}

커스텀 라벨 (Custom labels)

confirmLabel과 cancelLabel을 사용해 버튼 텍스트를 액션에 맞게 조정할 수 있어요.

<ChatConfirmation
  message="Send this email on your behalf?"
  confirmLabel="Send email"
  cancelLabel="Cancel"
  onConfirm={handleConfirm}
  onCancel={handleCancel}
/>

어댑터에 연결하기 (Connecting to the adapter)

카드 표시 여부를 React.useState에 보관하세요. 에이전트가 확인 단계를 트리거하면 카드를 표시하고, 사용자가 응답하면 숨깁니다.

const [pendingConfirmation, setPendingConfirmation] = React.useState(false);

const setConfirmRef = React.useRef(setPendingConfirmation);
setConfirmRef.current = setPendingConfirmation;

const adapter = React.useMemo(
  () => ({
    async sendMessage({ message }) {
      // ... stream agent response ...
      // Signal that a confirmation is needed:
      setConfirmRef.current(true);
      return responseStream;
    },
  }),
  [],
);

// In your JSX:
{
  pendingConfirmation && (
    <ChatConfirmation
      message="Proceed with this action?"
      onConfirm={() => {
        setPendingConfirmation(false);
        /* approve the tool */
      }}
      onCancel={() => setPendingConfirmation(false)}
    />
  );
}

도구 호출 승인과의 관계 (Relationship to tool-call approval)

내장 도구 부분(part)의 approval-requested 상태는 특정 도구 호출을 승인하는 좁은 범위를 처리해요. 접을 수 있는(collapsible) 도구 위젯 안에 렌더링됩니다. ChatConfirmation은 구조화된 도구 호출을 요구하지 않는 모든 "human-in-the-loop" 체크포인트를 위한 더 넓고 눈에 띄는 패턴이에요.

다음 경우에는 스트림 기반 tool-approval-request를 사용하세요.

  • 승인이 특정 도구 호출과 연결된 경우
  • 승인 UI를 메시지 안에 인라인으로 두고 싶은 경우
  • 백엔드가 승인 후 스트림을 재개해야 하는 경우

다음 경우에는 ChatConfirmation을 사용하세요.

  • 페이지 수준의 눈에 띄는 확인 다이얼로그가 필요한 경우
  • 확인이 특정 도구 호출과 연결되지 않은 경우
  • 확인 UI와 흐름을 완전히 제어하고 싶은 경우

도구 승인을 위한 커스텀 렌더러 등록 (Registering custom renderers for tool approval)

도구 부분 안에서 approval-requested 상태를 처리하는 렌더러를 등록하세요.

const renderers: ChatPartRendererMap = {
  tool: ({ part, message, index }) => {
    const { toolInvocation } = part;

    if (toolInvocation.state === 'approval-requested') {
      return (
        <ApprovalCard
          toolName={toolInvocation.toolName}
          input={toolInvocation.input}
          onApprove={() =>
            addToolApprovalResponse({
              id: toolInvocation.approvalId ?? toolInvocation.toolCallId,
              approved: true,
            })
          }
          onDeny={(reason) =>
            addToolApprovalResponse({
              id: toolInvocation.approvalId ?? toolInvocation.toolCallId,
              approved: false,
              reason,
            })
          }
        />
      );
    }

    return <ToolCard invocation={toolInvocation} />;
  },
};

<ChatProvider adapter={adapter} partRenderers={renderers}>
  <MyChat />
</ChatProvider>;

접근성 (Accessibility)

  • ChatConfirmation은 메시지로 표시되는 인라인, 모달이 아닌 group이에요. 포커스를 가져가거나 가두지 않으므로 메시지 흐름 속에 자연스럽게 자리합니다.
  • 의도적으로 alertdialog가 아닙니다. 그 역할은 카드가 제공하지도 필요로 하지도 않는 모달 포커스 관리를 약속합니다. 차단형 확인이 필요하다면 자신의 모달 안(예: MUI Dialog)에 렌더링하고 거기서 포커스를 관리하세요.
  • 내장 인라인 도구 위젯의 Approve와 Deny 컨트롤은 네이티브 button 요소이며, 응답이 처리되는 동안 비활성화됩니다.

채팅 UI의 전체 키보드 모델과 ARIA 구조는 Accessibility 페이지를 참고하세요.

함께 보기 (See also)

  • 전체 도구 호출 수명주기와 chunk 프로토콜에 대한 자세한 내용은 Tool calling을 참고하세요.
  • 승인 응답 메서드에 대한 자세한 내용은 Adapter를 참고하세요.
  • tool-approval-request chunk 타입에 대한 자세한 내용은 Streaming을 참고하세요.
  • 도구 호출과 함께 LLM 사고(reasoning)를 표시하는 방법은 Reasoning을 참고하세요.

ChatConfirmation API

데모 (Demos)

이 React 컴포넌트 사용법에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 참고하세요.

가져오기 (Import)

import { ChatConfirmation } from '@mui/x-chat/ChatConfirmation';
// or
import { ChatConfirmation } from '@mui/x-chat';

Props

Name Type Default Required Description
message string - Yes
cancelLabel string 'Cancel' No
confirmLabel string 'Confirm' No
onCancel func - No
onConfirm func - No

Note: The ref is forwarded to the root element.

Any other props supplied will be provided to the root element (native element).

CSS

규칙 이름 (Rule name)

Global class Rule name Description
- actions Styles applied to the actions container element.
- cancelButton Styles applied to the cancel button element.
- confirmButton Styles applied to the confirm button element.
- icon Styles applied to the icon element.
- message Styles applied to the message element.
- root Styles applied to the root element.

소스 코드 (Source code)

이 페이지에서 정보를 찾지 못했다면, 컴포넌트 구현을 살펴보는 것을 고려해 보세요.

더 알아보기 (Learn more)