게시일: 2026년 5월 18일, 최종 업데이트: 2026년 10월 16일
| 설명하듯이 | 웹 | 확장 프로그램 | Chrome 상태 | 의도 |
|---|---|---|---|---|
| GitHub | View | 실험 의도 |
WebMCP Imperative 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인 경우 도구를 실행하면 중요하거나 실제적이거나 되돌릴 수 없는 작업 (예: 항공편 예약, 송금, 데이터 삭제)이 발생함을 나타냅니다. 이를 통해 에이전트와 브라우저는 중요한 도구를 실행하기 전에 필수 사용자 확인 메시지를 표시하여 사용자 의도가 실수로 또는 악의적으로 잘못 표현될 위험을 완화할 수 있습니다.debugging(불리언, 기본값은false, Chrome 156부터 사용 가능):true인 경우 도구가 최종 사용자 상호작용이 아닌 검사 및 개발자 도구 (예: 테스트 프레임워크 또는 Chrome DevTools AI 지원)를 위해 특별히 설계되었음을 나타냅니다. 이렇게 하면 범용 및 최종 사용자 에이전트가 개발자 중심 도구를 필터링할 수 있습니다.
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,
debugging: false,
},
execute: async ({ flightId, passengers }) => {
// Add your flight booking transaction logic here.
return `Booked ${passengers} passenger(s) on flight ${flightId}.`;
},
});
주석이 에이전트 동작에 미치는 영향에 관한 예시는 WebMCP 확장 프로그램 예시를 참고하세요.
도구 등록 취소
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, debugging: 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 옵션에 출처를 명시적으로 나열해야 합니다. 이 배열은 보안 출처만 지원합니다.
교차 출처 문서의 도구는 다음 경우에만 포함됩니다.
- 호스팅 출처는
fromOrigins옵션에 나열됩니다. - 도구가 출처에 명시적으로 노출되었습니다.
// 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 페이지 에이전트 데모를 참고하세요. 예시 WebMCP 확장 프로그램을 참고하여 브라우저 확장 프로그램의 에이전트가 동일 출처 및 교차 출처 iframe에서 도구를 찾고 실행하는 방법을 확인하세요.
도구 실행
getTools()에서 발견된 도구를 수동으로 실행하려면 JSON 문자열로 직렬화할 수 있는 입력 인수에 대한 선택적 JavaScript 객체와 함께 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는 use-webmcp-tool 패키지를 사용하여 WebMCP를 실험적으로 지원합니다. 애플리케이션이 이미 React로 작성된 경우 구성요소의 마운트 및 마운트 해제 수명 주기에 연결된 useWebMCP 후크를 사용하여 도구를 등록할 수 있습니다. 또한 조건부 도구 등록을 지원하고 실행 결과를 자동으로 정규화합니다.
Angular 지원
Angular는 WebMCP를 실험적으로 지원합니다. 애플리케이션이 이미 Angular로 작성된 경우 애플리케이션의 종속 항목 삽입 수명 주기에 연결된 도구를 등록하고 Signal Forms를 WebMCP 도구로 전환할 수 있습니다.
Vue 지원
Vue는 @vueuse/core 패키지를 사용하여 WebMCP를 실험적으로 지원합니다. 애플리케이션이 이미 Vue로 작성된 경우 현재 Vue 범위 수명 주기에 연결된 useWebMCP 컴포저블을 사용하여 도구를 등록할 수 있습니다. 또한 사후 대응적 및 조건부 도구 등록을 지원하고 실행 결과를 자동으로 정규화합니다.
참여 및 의견 공유
WebMCP는 현재 활발히 논의 중이며 향후 변경될 수 있습니다. 이 API를 사용해 보고 의견이 있으면 알려주세요.
- WebMCP 설명서를 읽고 질문을 제기하고 토론에 참여하세요.
- 효과적인 WebMCP 도구를 빌드하는 방법과 WebMCP 권장사항을 읽어보세요.
- Chrome 상태에서 Chrome 구현을 검토합니다.
- 초기 프리뷰 프로그램에 참여하여 새로운 API를 미리 살펴보고 메일링 리스트에 액세스하세요.
- Chrome 구현에 관한 의견이 있으면 Chromium 버그를 신고하세요.