명령형 API

Alexandra Klepper
Alexandra Klepper
François Beaufort
François Beaufort

게시일: 2026년 5월 18일, 최종 업데이트: 2026년 9월 1일

설명 동영상 확장 프로그램 Chrome 상태 의도
GitHub 오리진 트라이얼 오리진 트라이얼 View 실험 의도

WebMCP 명령형 API를 사용하여 표준 JavaScript로 여러 유형의 도구를 정의할 수 있습니다. 도구는 양식 입력, 사이트 탐색, 상태 관리와 같은 다양한 함수를 실행할 수 있습니다.

이 API를 사용하기 전에 사용 사례를 읽어보세요.

모델 컨텍스트 제공

modelContext 인터페이스를 사용하여 도구를 등록합니다. 도구를 등록하려면 이름, 설명, 관련 속성이 있는 입력 스키마가 필요합니다.

registerTool을 사용하여 모델 컨텍스트에 단일 도구를 추가합니다.

WebMCPza Maker

await document.modelContext.registerTool({
  name: 'toggle_layer',
  description: 'Control pizza layers (sauce, cheese). Use "add", "remove", or "toggle".',
  inputSchema: {
    type: 'object',
    properties: {
      layer: { type: 'string', enum: ['sauce-layer', 'cheese-layer'] },
      action: { type: 'string', enum: ['add', 'remove', 'toggle'] },
    },
    required: ['layer'],
  },
  execute: async ({ layer, action }) => {
    await toggleLayer(layer, action);
    return `Performed ${action || 'toggle'} on layer: ${layer}`;
  },
});

주문 상태 가져오기

await document.modelContext.registerTool({
  name: 'get_order_status',
  description: 'Search orders in a given timeframe. Returns order number, shipping status and location',
  inputSchema: {
    "type": "object",
    "properties": {
      "timeframe": { "type": "string", "oneOf": [
        { "type": "string", "const": "today", "title": "Today" },
        { "type": "string", "const": "yesterday", "title": "Yesterday" },
        { "type": "string", "const": "last_7_days", "title": "Last 7 Days" },
        { "type": "string", "const": "last_30_days", "title": "Last 30 Days" },
        { "type": "string", "const": "last_6_months", "title": "Last 6 Months" }],
      "enum": [ "today", "yesterday", "last_7_days", "last_30_days", "last_6_months" ],
      "description": "Timeframe for the order lookup." }
    },
    "required": [ "timeframe" ]
  },
  execute: async ({ timeframe }) => {
    // Add your API or database logic here to fetch and return the order data as a string.
  },
});

도구 주석 (선택사항)

도구를 등록할 때 annotations 속성에 메타데이터 힌트를 추가할 수 있습니다. 이러한 힌트는 에이전트와 브라우저가 도구의 안전 특성, 예상되는 부작용, 출력 신뢰도를 이해하는 데 도움이 됩니다.

  • readOnlyHint (부울, 기본값은 false): true인 경우 도구가 정보만 읽고 애플리케이션 또는 시스템의 상태를 수정하지 않음을 나타냅니다 (예: 제품 카탈로그 검색 또는 주문 상태 가져오기). 이를 통해 에이전트는 부작용 없이 도구를 안전하게 호출할 수 있는지 확인할 수 있습니다.
  • untrustedContentHint (부울, 기본값은 false): true인 경우 도구의 출력에 도구 작성자의 관점에서 신뢰할 수 없는 데이터가 포함되어 있음을 나타냅니다 (예: 사용자 제작 콘텐츠, 리뷰 또는 외부 웹 데이터). 이는 에이전트와 클라이언트에 반환된 페이로드 가 간접 프롬프트 인젝션을 완화하기 위해 삭제 또는 구분과 같은 강화된 보안 처리가 필요함을 알립니다.
  • consequentialHint (부울, 기본값은 false): true인 경우 도구를 실행하면 중요한 실제 또는 되돌릴 수 없는 작업이 발생함을 나타냅니다 (예: 항공편 예약, 송금 또는 데이터 삭제). 이를 통해 에이전트와 브라우저는 위험도가 높은 도구를 실행하기 전에 필수 사용자 확인 프롬프트를 적용하여 사용자 의도를 실수로 또는 악의적으로 허위 진술할 위험을 완화할 수 있습니다.
await document.modelContext.registerTool({
  name: 'book_flight',
  description: 'Book a flight for the user with confirmed flight details.',
  inputSchema: {
    type: 'object',
    properties: {
      flightId: { type: 'string', description: 'ID of the flight to book' },
      passengers: { type: 'number', description: 'Number of tickets to purchase' },
    },
    required: ['flightId', 'passengers'],
  },
  annotations: {
    readOnlyHint: false,
    consequentialHint: true,
    untrustedContentHint: false,
  },
  execute: async ({ flightId, passengers }) => {
    // Add your flight booking transaction logic here.
    return `Booked ${passengers} passenger(s) on flight ${flightId}.`;
  },
});

도구 등록 취소

선택적 매개변수로 전달된 경우 AbortSignal을 사용하여 도구를 삭제할 수 있습니다.

const addTodoTool = {
  name: "addTodo",
  description: "Add a new item to the to-do list",
  inputSchema: {
    type: "object",
    properties: { text: { type: "string" } },
  },
  execute: async ({ text }) => {
    // You should handle the persistence logic here (omitted for demo)
    return `Added to-do: ${text}`;
  },
  annotations: {
    readOnlyHint: false,
    untrustedContentHint: true
  },
};
const controller = new AbortController();
await document.modelContext.registerTool(addTodoTool, { signal: controller.signal });

// Unregister the tool later...
controller.abort();

Chrome 153부터 진행 중인 실행을 취소하거나 중단하지 않고 도구를 등록 취소할 수 있습니다. 이렇게 하면 구성요소 프레임워크에서 도구 수명 주기를 관리할 때 예기치 않은 부작용이 발생하지 않습니다.

도구 취소 처리

execute 함수는 사용자 또는 에이전트가 시작한 실행 취소를 정상적으로 처리하기 위해 signal이라는 AbortSignal 매개변수를 두 번째 인수로 수신합니다. 이 신호를 장기 실행 비동기 작업 또는 네트워크 작업 (예: fetch())에 전달하면 불필요한 작업을 방지하고 전반적인 리소스 관리를 개선하며 잠재적인 누수를 방지할 수 있습니다.

await document.modelContext.registerTool({
  name: 'fetch_tool',
  description: 'Fetch the text content of a URL and stream the response.',
  inputSchema: {
    type: 'object',
    properties: {
      url: { type: 'string', description: 'The URL to fetch' },
      priority: { type: 'string', enum: ['high', 'low', 'auto'] },
    },
    required: ['url'],
  },
  execute: async ({ url, priority }, { signal }) => {
    // Abort the fetch request when tool execution is aborted.
    const response = await fetch(url, { priority, signal });
    const stream = response.body.pipeThrough(new TextDecoderStream());
    for await (const chunk of stream) {
      document.querySelector('pre').textContent += chunk;
    }
    return 'Success';
  },
});

도구 탐색

document.modelContext.getTools()를 사용하여 사용 가능한 도구를 가져옵니다. 이 비동기 메서드는 호출 문서가 액세스할 수 있는 권한이 있는 도구의 알파벳순으로 정렬된 목록을 반환합니다.

const [tool] = await document.modelContext.getTools();
console.log(tool);

// {
//   annotations: { consequentialHint: false, readOnlyHint: false, untrustedContentHint: true }, // Optional hints
//   description: "Add a new item to the to-do list",
//   inputSchema: {"type":"object","properties":{…}},
//   name: "addTodo",
//   origin: "https://example.com",
//   title: ""
//   window: Window {window: Window, self: Window, …},
// }

기본적으로 getTools()는 호출 문서 또는 프레임 트리의 다른 동일 출처 문서에 의해 등록된 동일 출처 도구만 반환합니다. 교차 출처 도구를 가져오려면 fromOrigins 옵션에서 출처를 명시적으로 나열해야 합니다. 이 배열은 보안 출처만 지원합니다.

교차 출처 문서의 도구는 다음과 같은 경우에만 포함됩니다.

  1. 호스팅 출처가 fromOrigins 옵션에 나열되어 있습니다.
  2. 도구가 출처에 명시적으로 노출되었습니다.
// https://example.com

// Get same-origin tools only
const sameOriginTools = await document.modelContext.getTools();

// Get same-origin tools plus tools from specific cross-origin documents
const allTools = await document.modelContext.getTools({
  fromOrigins: ['https://partner.org']
});

iframe에서 도구를 가져와 웹 기반 채팅 인터페이스 내에서 실행하는 방법의 예는 WebMCP 페이지 에이전트 데모 를 참고하세요.

도구 실행

getTools()에서 발견된 도구를 수동으로 실행하려면 입력 인수를 유효한 JSON 문자열로 사용하여 document.modelContext.executeTool()을 호출합니다. 이 비동기 메서드는 도구 실행 결과를 반환하거나 탐색이 트리거될 때 null을 반환합니다.

const result = await document.modelContext.executeTool(tool, '{"text": "Buy milk"}');
console.log(result);

// 'Added to-do: Buy milk'

선택적 매개변수로 전달된 경우 AbortSignal을 사용하여 대기 중인 도구 실행을 취소할 수 있습니다.

const controller = new AbortController();
document.modelContext.executeTool(tool, '{"text": "Buy milk"}', {
  signal: controller.signal,
});

// Cancel tool execution later...
controller.abort();

이벤트

프레임은 사용 가능한 도구 목록이 변경될 때 알림을 받기 위해 document.modelContext에서 toolchange 이벤트를 수신 대기할 수 있습니다.

document.modelContext.addEventListener("toolchange", (event) => {
  // Tools have changed.
});

교차 출처 iframe

WebMCP는 권한 정책과 명시적 출처 게이팅을 모두 사용하는 교차 출처 iframe을 지원합니다.

권한 정책

교차 출처 iframe에서는 도구 등록이 기본적으로 사용 중지되어 있습니다. 페이지는 tools 권한 정책을 사용하여 액세스 권한을 위임해야 합니다.

<iframe src="https://example.com" allow="tools"></iframe>

출처 노출

도구는 기본적으로 교차 출처 문서에서 사용할 수 없습니다. registerTool 내에서 exposedTo 배열을 사용하여 도구를 보고 실행할 수 있는 특정 출처를 나열할 수 있습니다. 이 배열은 보안 출처만 지원합니다.

// https://partner.org

await document.modelContext.registerTool({
  name: 'my_shared_tool',
  description: 'Shared across origins',
  // ...
}, {
  exposedTo: ['https://example.com']
});

React 지원

React는 WebMCP를 실험적으로 지원합니다 usewebmcp 패키지를 사용하여. 애플리케이션이 이미 React로 작성된 경우 구성요소의 마운트 및 마운트 해제 수명 주기에 연결된 독립형 후크를 사용하여 도구를 등록할 수 있습니다. useWebMCP 후크는 스키마 기반 유형 추론도 제공하고 로컬 실행 상태를 노출합니다.

Angular 지원

Angular는 WebMCP를 실험적으로 지원합니다. 애플리케이션이 이미 Angular로 작성된 경우 애플리케이션의 종속 항목 삽입 수명 주기에 연결된 도구를 등록하고 신호 양식을 WebMCP 도구로 전환할 수 있습니다.

참여 및 의견 공유

WebMCP는 현재 논의 중이며 향후 변경될 수 있습니다. 이 API를 사용해 보고 의견이 있으면 알려주세요.