콘텐츠로 이동

도구

도구를 사용하면 에이전트가 데이터 가져오기, 외부 API 호출, 코드 실행, 컴퓨터 사용 등의 작업을 수행할 수 있습니다. JavaScript/TypeScript SDK는 다음 7가지 카테고리를 지원합니다.

어떤 에이전트가 작업을 담당할지 결정하고 기능을 부여하려면 에이전트를 읽은 후 이 페이지를 살펴보세요. 아직 위임 패턴을 결정하는 중이라면 에이전트 오케스트레이션을 참고하세요.

  1. OpenAI 호스티드 툴 – OpenAI 서버에서 모델과 함께 실행됩니다. (웹 검색, 파일 검색, Code Interpreter, 이미지 생성, 도구 검색)
  2. 기본 제공 실행 도구 – SDK에서 제공하며 모델 외부에서 실행되는 도구입니다. (컴퓨터 사용과 apply_patch는 로컬에서 실행되며, shell은 로컬 또는 호스티드 컨테이너에서 실행할 수 있음)
  3. 함수 도구 – LLM이 호출할 수 있도록 모든 로컬 함수를 JSON 스키마로 래핑합니다.
  4. Agents as tools – 전체 에이전트를 호출 가능한 도구로 노출합니다.
  5. MCP 서버 – Model Context Protocol 서버를 연결합니다(로컬 또는 원격).
  6. 샌드박스 기능 – 작업 공간 범위의 shell, 파일 시스템, 스킬, 메모리 또는 압축 도구를 SandboxAgent에 연결합니다.
  7. 실험적 기능: Codex 도구 – 작업 공간을 인식하는 작업을 실행하도록 Codex SDK를 함수 도구로 래핑합니다.

이 가이드의 나머지 부분에서는 먼저 각 도구 카테고리를 설명한 다음, 여러 카테고리에 공통으로 적용되는 도구 선택 및 프롬프팅 지침을 요약합니다.

OpenAIResponsesModel을 사용할 때 다음과 같은 기본 제공 도구를 추가할 수 있습니다.

도구타입 문자열용도
웹 검색'web_search'인터넷 검색
파일/검색'file_search'OpenAI에서 호스팅하는 벡터 스토어 쿼리
Code Interpreter'code_interpreter'샌드박스 환경에서 코드 실행
이미지 생성'image_generation'텍스트를 기반으로 이미지 생성
도구 검색'tool_search'런타임에 지연된 함수 도구, 네임스페이스 또는 검색 가능한 MCP 도구 로드
호스티드 툴
import {
Agent,
codeInterpreterTool,
fileSearchTool,
imageGenerationTool,
webSearchTool,
} from '@openai/agents';
const agent = new Agent({
name: 'Travel assistant',
tools: [
webSearchTool({ searchContextSize: 'medium' }),
fileSearchTool('VS_ID', { maxNumResults: 3 }),
codeInterpreterTool(),
imageGenerationTool({ size: '1024x1024' }),
],
});

SDK는 호스티드 툴 정의를 반환하는 헬퍼 함수를 제공합니다.

헬퍼 함수참고 사항
webSearchTool(options?)searchContextSize, userLocation, filters.allowedDomains 등 JavaScript 친화적인 옵션
fileSearchTool(ids, options?)첫 번째 인수로 하나 이상의 벡터 스토어 ID를 받고 maxNumResults, includeSearchResults, rankingOptions, 필터 등의 옵션도 지원
codeInterpreterTool(options?)container를 제공하지 않으면 자동 관리형 컨테이너가 기본값
imageGenerationTool(options?)model, size, quality, background, inputFidelity, inputImageMask, moderation, outputCompression, partialImages, 출력 형식 등의 이미지 생성 설정 지원
toolSearchTool(options?)기본 제공 tool_search 헬퍼 추가. deferLoading: true가 설정된 지연 함수 도구 또는 호스티드 MCP 도구와 함께 사용. 기본적으로 호스티드 실행을 지원하며, execution: 'client'execute를 사용한 클라이언트 실행도 지원

이러한 헬퍼는 JavaScript/TypeScript 친화적인 옵션 이름을 기반 OpenAI Responses API 도구 페이로드에 매핑합니다. 전체 도구 스키마와 순위 지정 옵션 또는 시맨틱 필터 같은 고급 옵션은 공식 OpenAI 도구 가이드를 참고하고, 현재 기본 제공 도구 검색 흐름과 모델 지원 여부는 공식 도구 검색 가이드를 참고하세요.


이러한 도구는 SDK에 기본 제공되지만, 실행은 모델 응답 자체의 외부에서 이루어집니다.

  • 컴퓨터 사용Computer 인터페이스를 구현하고 computerTool()에 전달합니다. 항상 사용자가 제공한 로컬 Computer 구현을 대상으로 실행됩니다.
  • Shell – 로컬 Shell 구현을 제공하거나 shellTool({ environment })를 사용하여 호스티드 컨테이너 환경을 설정합니다.
  • 패치 적용Editor 인터페이스를 구현하고 applyPatchTool()에 전달합니다. 항상 사용자가 제공한 로컬 Editor 구현을 대상으로 실행됩니다.
  • 샌드박스 shell 및 파일 시스템 도구 – 샌드박스 작업 공간 안에서 작업을 실행해야 할 때 SandboxAgent에서 shell(), filesystem(), skills(), memory() 또는 compaction()을 사용합니다.

도구 호출은 여전히 모델이 요청하지만, 실제 작업은 애플리케이션이나 설정된 실행 환경에서 수행합니다.

샌드박스 기능 도구는 프로세스 전체에 적용되는 기본 제공 도구와 다릅니다. 현재 SandboxAgent 실행의 활성 샌드박스 세션에 바인딩됩니다. 도구가 애플리케이션 프로세스 대신 에이전트의 격리된 작업 공간에서 작동해야 한다면 빠른 시작을 사용하세요.

기본 제공 실행 도구
import {
Agent,
applyPatchTool,
computerTool,
shellTool,
Computer,
Editor,
Shell,
} from '@openai/agents';
const computer: Computer = {
environment: 'browser',
dimensions: [1024, 768],
screenshot: async () => '',
click: async () => {},
doubleClick: async () => {},
scroll: async () => {},
type: async () => {},
wait: async () => {},
move: async () => {},
keypress: async () => {},
drag: async () => {},
};
const shell: Shell = {
run: async () => ({
output: [
{
stdout: '',
stderr: '',
outcome: { type: 'exit', exitCode: 0 },
},
],
}),
};
const editor: Editor = {
createFile: async () => ({ status: 'completed' }),
updateFile: async () => ({ status: 'completed' }),
deleteFile: async () => ({ status: 'completed' }),
};
const agent = new Agent({
name: 'Local tools agent',
model: 'gpt-5.4',
tools: [
computerTool({ computer }),
shellTool({ shell, needsApproval: true }),
applyPatchTool({ editor, needsApproval: true }),
],
});

computerTool()은 다음 중 하나를 받습니다.

  • 구체적인 Computer 인스턴스
  • 실행마다 Computer를 생성하는 초기화 함수
  • 실행 범위의 설정 및 해제가 필요한 경우 { create, dispose }를 포함하는 공급자 객체

OpenAI의 현재 컴퓨터 사용 경로를 사용하려면 gpt-5.4처럼 컴퓨터 기능을 지원하는 모델을 설정하세요. 요청 모델을 명시하면 SDK는 GA 기본 제공 computer 도구 형식을 전송합니다. 유효 모델을 저장된 프롬프트나 다른 이전 연동에서 계속 가져오는 경우, modelSettings.toolChoice: 'computer'를 사용하여 GA 경로를 명시적으로 선택하지 않는 한 SDK는 호환성을 위해 레거시 computer_use_preview 전송 형식을 유지합니다.

GA 컴퓨터 호출은 하나의 computer_call에 일괄 처리된 actions[]를 포함할 수 있습니다. SDK는 이를 순서대로 실행하고 각 작업에 대해 needsApproval을 평가한 다음, 최종 스크린샷을 도구 출력으로 반환합니다. interruption.rawItem에서 승인 UI를 구축하는 경우 actions가 있으면 이를 읽고, 없으면 레거시 미리 보기 항목의 action을 사용하세요.

영향이 큰 컴퓨터 작업을 사용자 검토를 위해 일시 중지해야 할 때는 needsApproval을 사용하고, 컴퓨터 호출에 보고된 보류 중인 안전성 검사를 승인하거나 거부하려면 onSafetyCheck를 사용하세요. 모델 측 지침과 마이그레이션 세부 정보는 공식 OpenAI 컴퓨터 사용 가이드와 해당 마이그레이션 참고 사항을 참고하세요.

shellTool()에는 두 가지 모드가 있습니다.

  • 로컬 모드: shell을 제공하고, 선택적으로 environment: { type: 'local', skills }와 자동 승인 처리를 위한 needsApprovalonApproval을 제공합니다.
  • 호스티드 컨테이너 모드: type: 'container_auto' 또는 type: 'container_reference'가 포함된 environment를 제공합니다.

로컬 모드에서 environment.skills를 사용하면 name, description, 파일 시스템 path를 기준으로 로컬 스킬을 마운트할 수 있습니다.

호스티드 컨테이너 모드에서는 다음 중 하나를 사용하여 shellTool({ environment })를 설정합니다.

  • 실행을 위한 관리형 컨테이너를 생성하려면 type: 'container_auto'
  • containerId로 기존 컨테이너를 재사용하려면 type: 'container_reference'

호스티드 container_auto 환경은 다음을 지원합니다.

  • domainSecrets가 있는 허용 목록을 포함한 networkPolicy
  • 업로드한 파일을 마운트하기 위한 fileIds
  • 컨테이너 크기 조정을 위한 memoryLimit
  • skill_reference 또는 인라인 zip 번들로 제공되는 skills

호스티드 shell 환경은 로컬 프로세스가 아닌 호스티드 컨테이너 환경에서 실행되므로 shell, needsApproval, onApproval을 받지 않습니다.

전체 사용법은 examples/tools/local-shell.ts, examples/tools/container-shell-skill-ref.ts, examples/tools/container-shell-inline-skill.ts를 참고하세요.

applyPatchTool()shellTool()의 로컬 승인 흐름을 그대로 따릅니다. 파일 편집 전에 일시 중지하려면 needsApproval을 사용하고, 애플리케이션 수준 콜백에서 자동 승인 또는 거부하려면 onApproval을 사용하세요.


tool() 헬퍼를 사용하면 어떤 함수든 도구로 만들 수 있습니다.

Zod 매개변수를 사용하는 함수 도구
import { tool } from '@openai/agents';
import { z } from 'zod';
const getWeatherTool = tool({
name: 'get_weather',
description: 'Get the weather for a given city',
parameters: z.object({ city: z.string() }),
async execute({ city }) {
return `The weather in ${city} is sunny.`;
},
});
필드필수설명
name아니요기본값은 함수 이름입니다(예: get_weather).
descriptionLLM에 표시되는 명확하고 사람이 이해하기 쉬운 설명입니다.
parametersZod 스키마 또는 원문 JSON 스키마 객체입니다. Zod 매개변수는 자동으로 엄격 모드를 활성화합니다.
strict아니요true(기본값)이면 인수의 유효성 검사에 실패할 때 SDK가 모델 오류를 반환합니다. 유연한 일치를 사용하려면 false로 설정합니다.
execute(args, context, details) => string | unknown | Promise<...> – 비즈니스 로직입니다. 문자열이 아닌 출력은 모델을 위해 직렬화됩니다. context는 선택적인 RunContext이며, details에는 toolCall, resumeState, signal 같은 메타데이터가 포함됩니다.
errorFunction아니요내부 오류를 사용자에게 표시되는 문자열로 변환하는 사용자 지정 핸들러 (context, error) => string입니다.
timeoutMs아니요호출별 제한 시간(밀리초)입니다. 0보다 크고 2147483647 이하여야 합니다.
timeoutBehavior아니요제한 시간 모드입니다. error_as_result(기본값)는 모델에 표시되는 제한 시간 메시지를 반환하고, raise_exceptionToolTimeoutError를 발생시킵니다.
timeoutErrorFunction아니요timeoutBehaviorerror_as_result일 때 제한 시간 출력을 처리하는 사용자 지정 핸들러 (context, timeoutError) => string입니다.
customDataExtractor아니요생성되는 RunToolCallOutputItem.customData에 SDK 전용 메타데이터를 첨부하는 콜백 (context) => Record<string, unknown> | null | undefined입니다. 이 데이터는 모델로 다시 전송되지 않습니다.
needsApproval아니요실행 전에 사람의 승인이 필요합니다. 휴먼 인 더 루프 (HITL)를 참고하세요.
isEnabled아니요실행별로 도구 노출 여부를 조건부로 결정합니다. 부울 값이나 조건자를 받습니다.
inputGuardrails아니요도구 실행 전에 실행되며 요청을 거부하거나 예외를 발생시킬 수 있는 가드레일입니다. 가드레일을 참고하세요.
outputGuardrails아니요도구 실행 후에 실행되며 결과를 거부하거나 예외를 발생시킬 수 있는 가드레일입니다. 가드레일을 참고하세요.

애플리케이션에서 도구 결과와 함께 렌더러 힌트, 내부 ID 또는 기타 JSON 호환 메타데이터가 필요할 때 customDataExtractor를 사용하세요. 콜백은 실행 컨텍스트, 도구 정의, 모델 도구 호출, 파싱된 입력, 출력, 복제된 원문 출력 항목을 받습니다. 반환된 데이터는 RunToolCallOutputItem.customDataRunState에 저장되지만 history 및 모델 재실행에서는 제외됩니다.

각 함수 도구 호출의 실행 시간을 제한하려면 timeoutMs를 사용하세요.

  • timeoutBehavior: 'error_as_result'(기본값)는 모델에 Tool '<name>' timed out after <timeoutMs>ms.를 반환합니다.
  • timeoutBehavior: 'raise_exception'ToolTimeoutError를 발생시키며, 실행 예외의 일부로 처리할 수 있습니다.
  • timeoutErrorFunction을 사용하면 error_as_result 모드의 제한 시간 텍스트를 사용자 지정할 수 있습니다.
  • 제한 시간이 초과되면 details.signal이 중단되므로, 장시간 실행되는 도구가 취소를 수신하면 신속하게 중지할 수 있습니다.

함수 도구를 직접 호출하는 경우 invokeFunctionTool을 사용하여 일반 에이전트 실행과 동일한 제한 시간 동작을 적용하세요.

모델이 유효하지 않거나 불완전한 입력을 추론해야 한다면 원문 JSON 스키마를 사용할 때 엄격 모드를 비활성화할 수 있습니다.

비엄격 JSON 스키마 도구
import { tool } from '@openai/agents';
interface LooseToolInput {
text: string;
}
const looseTool = tool({
description: 'Echo input; be forgiving about typos',
strict: false,
parameters: {
type: 'object',
properties: { text: { type: 'string' } },
required: ['text'],
additionalProperties: true,
},
execute: async (input) => {
// because strict is false we need to do our own verification
if (typeof input !== 'object' || input === null || !('text' in input)) {
return 'Invalid input. Please try again';
}
return (input as LooseToolInput).text;
},
});

도구 검색을 통한 지연된 도구 로드

섹션 제목: “도구 검색을 통한 지연된 도구 로드”

도구 검색을 사용하면 모든 스키마를 미리 전송하는 대신 모델이 런타임에 필요한 도구 정의만 로드할 수 있습니다. SDK에서는 이를 통해 지연된 최상위 함수 도구, toolNamespace() 그룹, deferLoading: true로 설정된 호스티드 MCP 도구를 사용할 수 있습니다.

도구 검색은 Responses API에서 이를 지원하는 GPT-5.4 이상의 모델 릴리스에서만 사용하세요.

도구 검색을 통한 지연된 도구 로드
import { Agent, tool, toolNamespace, toolSearchTool } from '@openai/agents';
import { z } from 'zod';
const customerIdParams = z.object({
customerId: z.string().describe('The customer identifier to look up.'),
});
// Keep a standalone deferred tool at the top level when it represents a
// single searchable capability that does not need a shared namespace.
const shippingLookup = tool({
name: 'get_shipping_eta',
description: 'Look up a shipment ETA by customer identifier.',
parameters: customerIdParams,
deferLoading: true,
async execute({ customerId }) {
return {
customerId,
eta: '2026-03-07',
carrier: 'Priority Express',
};
},
});
// Group related tools into a namespace when one domain description should
// cover several deferred tools and let tool search load them together.
const crmTools = toolNamespace({
name: 'crm',
description: 'CRM tools for customer profile lookups.',
tools: [
tool({
name: 'get_customer_profile',
description: 'Fetch a basic customer profile.',
parameters: customerIdParams,
deferLoading: true,
async execute({ customerId }) {
return {
customerId,
tier: 'enterprise',
};
},
}),
],
});
const agent = new Agent({
name: 'Operations assistant',
model: 'gpt-5.4',
// Mixing namespaced and top-level deferred tools in one request is supported.
tools: [shippingLookup, ...crmTools, toolSearchTool()],
});

이 예제에서는 의도적으로 두 가지 방식을 함께 사용합니다.

  • shippingLookup은 독립적인 검색 기능 하나이므로 최상위에 유지됩니다.
  • crmTools는 관련 CRM 도구가 하나의 상위 수준 레이블과 설명을 공유하므로 toolNamespace()를 사용합니다.
  • 동일한 요청에서 네임스페이스가 지정된 지연 도구와 최상위 지연 도구를 함께 사용할 수 있습니다. 도구 검색은 crm 같은 네임스페이스 경로와 get_shipping_eta 같은 최상위 경로를 모두 로드할 수 있습니다.

도구 검색을 사용할 때는 다음 사항을 따르세요.

  • 각 지연 함수 도구에 deferLoading: true를 지정합니다.
  • 관련된 여러 도구가 하나의 도메인 설명을 공유하고 그룹으로 로드되어야 한다면 toolNamespace({ name, description, tools })를 사용합니다.
  • 독립적인 기능이 하나뿐이고 도구 이름 자체가 적절한 검색 대상이라면 도구를 최상위에 유지합니다.
  • 지연 함수 도구나 호스티드 MCP 도구에서 deferLoading: true를 사용할 때마다 동일한 tools 배열에 toolSearchTool()을 추가합니다.
  • modelSettings.toolChoice'auto'로 유지합니다. SDK는 기본 제공 tool_search 도구 또는 지연 함수 도구를 이름으로 강제 지정하는 것을 거부합니다.
  • 호스티드 실행이 기본값입니다. toolSearchTool({ execution: 'client', execute })를 설정하면 표준 run() 루프는 기본 제공 { paths: string[] } 클라이언트 쿼리 형식만 지원합니다. 사용자 지정 클라이언트 측 스키마에는 자체 Responses 루프가 필요합니다.
  • 하나의 네임스페이스에 즉시 로드되는 멤버와 지연 멤버를 함께 포함할 수 있습니다. 즉시 로드되는 멤버는 도구 검색 없이도 호출할 수 있고, 동일한 네임스페이스의 지연 멤버는 필요할 때 로드됩니다.
  • 지연 함수 도구와 toolNamespace()는 Responses에서만 사용할 수 있습니다. Chat Completions에서는 거부되며, AI SDK 어댑터는 지연된 Responses 도구 로드 흐름을 지원하지 않습니다.

대화를 완전히 핸드오프하지 않고 한 에이전트가 다른 에이전트를 지원하도록 하려는 경우가 있습니다. 이때 agent.asTool()을 사용합니다.

아직 agent.asTool()handoff() 중에서 선택하는 중이라면 에이전트 가이드에이전트 오케스트레이션에서 패턴을 비교하세요.

Agents as tools
import { Agent } from '@openai/agents';
const summarizer = new Agent({
name: 'Summarizer',
instructions: 'Generate a concise summary of the supplied text.',
});
const summarizerTool = summarizer.asTool({
toolName: 'summarize_text',
toolDescription: 'Generate a concise summary of the supplied text.',
});
const mainAgent = new Agent({
name: 'Research assistant',
tools: [summarizerTool],
});

내부적으로 SDK는 다음 작업을 수행합니다.

  • 단일 input 매개변수를 사용하는 함수 도구를 생성합니다.
  • 도구가 호출되면 해당 입력으로 하위 에이전트를 실행합니다.
  • 마지막 메시지 또는 customOutputExtractor가 추출한 출력을 반환합니다.

에이전트를 도구로 실행하면 Agents SDK는 기본 설정을 사용하는 러너를 생성하고 함수 실행 내에서 이를 사용해 에이전트를 실행합니다. runConfig 또는 runOptions의 속성을 제공하려면 이를 asTool() 메서드에 전달하여 러너 동작을 사용자 지정할 수 있습니다.

또한 asTool() 옵션을 통해 에이전트 도구에 needsApprovalisEnabled를 설정하여 휴먼인더루프 (HITL) 흐름 및 조건부 도구 가용성과 연동할 수 있습니다.

customOutputExtractor 내에서 현재 Agent.asTool() 호출을 검사하려면 result.agentToolInvocation을 사용하세요. 이 콜백의 결과는 항상 Agent.asTool()에서 나오므로 agentToolInvocation은 항상 정의되며 toolName, toolCallId, toolArguments를 노출합니다. 일반 애플리케이션 컨텍스트와 toolInput에는 result.runContext를 사용하세요. 이 메타데이터는 현재 중첩 호출로 범위가 제한되며 RunState로 직렬화되지 않습니다.

에이전트 도구 호출 메타데이터 읽기
import { Agent } from '@openai/agents';
const billingAgent = new Agent({
name: 'Billing Agent',
instructions: 'Handle billing questions and subscription changes.',
});
const billingTool = billingAgent.asTool({
toolName: 'billing_agent',
toolDescription: 'Handles customer billing questions.',
customOutputExtractor(result) {
console.log('tool', result.agentToolInvocation.toolName);
// Direct invoke() calls may not have a model-generated tool call id.
console.log('call', result.agentToolInvocation.toolCallId);
console.log('args', result.agentToolInvocation.toolArguments);
return String(result.finalOutput ?? '');
},
});
const orchestrator = new Agent({
name: 'Support Orchestrator',
instructions: 'Delegate billing questions to the billing agent tool.',
tools: [billingTool],
});

agent.asTool()의 고급 구조화 입력 옵션은 다음과 같습니다.

  • inputBuilder: 구조화된 도구 인수를 중첩 에이전트 입력 페이로드에 매핑합니다.
  • includeInputSchema: 스키마 인식 동작을 강화하도록 중첩 실행에 입력 JSON 스키마를 포함합니다.
  • resumeState: 직렬화된 중첩 RunState를 재개할 때 컨텍스트 조정 전략을 제어합니다. 'merge'(기본값)는 활성 승인/컨텍스트 상태를 직렬화된 상태에 병합하고, 'replace'는 현재 실행 컨텍스트를 대신 사용하며, 'preferSerialized'는 직렬화된 컨텍스트를 변경하지 않고 재개합니다.

에이전트 도구의 스트리밍 이벤트

섹션 제목: “에이전트 도구의 스트리밍 이벤트”

에이전트 도구는 중첩 실행 이벤트를 모두 애플리케이션으로 다시 스트리밍할 수 있습니다. 도구 구성 방식에 맞는 훅 스타일을 선택하세요.

에이전트 도구 스트리밍
import { Agent } from '@openai/agents';
const billingAgent = new Agent({
name: 'Billing Agent',
instructions: 'Answer billing questions and compute simple charges.',
});
const billingTool = billingAgent.asTool({
toolName: 'billing_agent',
toolDescription: 'Handles customer billing questions.',
// onStream: simplest catch-all when you define the tool inline.
onStream: (event) => {
console.log(`[onStream] ${event.event.type}`, event);
},
});
// on(eventName) lets you subscribe selectively (or use '*' for all).
billingTool.on('run_item_stream_event', (event) => {
console.log('[on run_item_stream_event]', event);
});
billingTool.on('raw_model_stream_event', (event) => {
console.log('[on raw_model_stream_event]', event);
});
const orchestrator = new Agent({
name: 'Support Orchestrator',
instructions: 'Delegate billing questions to the billing agent tool.',
tools: [billingTool],
});
  • 이벤트 타입은 RunStreamEvent['type']과 일치합니다. raw_model_stream_event, run_item_stream_event, agent_updated_stream_event
  • onStream은 가장 간단한 범용 방식이며 도구를 인라인으로 선언할 때 적합합니다(tools: [agent.asTool({ onStream })]). 이벤트별 라우팅이 필요하지 않을 때 사용하세요.
  • on(eventName, handler)을 사용하면 선택적으로 또는 '*'를 사용해 구독할 수 있으며, 더 세밀한 처리가 필요하거나 생성 후 리스너를 연결하려는 경우에 적합합니다.
  • onStream 또는 on(...) 핸들러를 하나라도 제공하면 Agents-as-tools는 자동으로 스트리밍 모드에서 실행됩니다. 제공하지 않으면 비스트리밍 경로를 유지합니다.
  • 핸들러는 병렬로 호출되므로 느린 onStream 콜백이 on(...) 핸들러를 차단하지 않으며, 그 반대도 마찬가지입니다.
  • 모델 도구 호출을 통해 도구를 호출하면 toolCallId가 제공됩니다. 직접 invoke()를 호출하거나 공급자 특성에 따라 생략될 수 있습니다.

Model Context Protocol (MCP) 서버를 통해 도구를 노출하고 에이전트에 연결할 수 있습니다. 예를 들어 MCPServerStdio를 사용하여 stdio MCP 서버를 생성하고 연결할 수 있습니다.

로컬 MCP 서버
import { Agent, MCPServerStdio } from '@openai/agents';
const server = new MCPServerStdio({
fullCommand: 'pnpm exec mcp-server-filesystem ./sample_files',
});
await server.connect();
const agent = new Agent({
name: 'Assistant',
mcpServers: [server],
});

전체 예제는 filesystem-example.ts를 참고하세요. MCP 서버 도구 연동에 관한 종합적인 가이드가 필요하다면 모델 컨텍스트 프로토콜 (MCP) 가이드에서 세부 정보를 확인하세요. 여러 서버 또는 부분적인 실패를 관리할 때는 connectMcpServers모델 컨텍스트 프로토콜 (MCP) 가이드의 수명 주기 지침을 사용하세요.


@openai/agents-extensions/experimental/codex는 모델 도구 호출을 Codex SDK로 라우팅하는 함수 도구인 codexTool()을 제공합니다. 이를 통해 에이전트가 작업 공간 범위의 작업(shell, 파일 편집, MCP 도구)을 자율적으로 실행할 수 있습니다. 이 인터페이스는 실험적이며 변경될 수 있습니다.

먼저 종속성을 설치합니다.

Terminal window
npm install @openai/agents-extensions @openai/codex-sdk

빠른 시작:

실험적 Codex 도구
import { Agent } from '@openai/agents';
import { codexTool } from '@openai/agents-extensions/experimental/codex';
export const codexAgent = new Agent({
name: 'Codex Agent',
instructions:
'Use the codex tool to inspect the workspace and answer the question. When skill names, which usually start with `$`, are mentioned, you must rely on the codex tool to use the skill and answer the question.',
tools: [
codexTool({
sandboxMode: 'workspace-write',
workingDirectory: '/path/to/repo',
defaultThreadOptions: {
model: 'gpt-5.4',
networkAccessEnabled: true,
webSearchEnabled: false,
},
}),
],
});

알아야 할 사항은 다음과 같습니다.

  • 인증: CODEX_API_KEY(권장) 또는 OPENAI_API_KEY를 제공하거나 codexOptions.apiKey를 전달합니다.
  • 입력: 엄격한 스키마를 사용하며 inputs에는 { type: 'text', text } 또는 { type: 'local_image', path }가 하나 이상 포함되어야 합니다.
  • 안전성: sandboxModeworkingDirectory와 함께 사용합니다. 디렉터리가 Git 저장소가 아니라면 skipGitRepoCheck를 설정합니다.
  • 스레딩: useRunContextThreadId: truerunContext.context에서 최신 스레드 ID를 읽고 저장합니다. 애플리케이션 상태에서 여러 턴에 걸쳐 재사용할 때 유용합니다.
  • 스레드 ID 우선순위: 도구 호출 threadId(스키마에 포함된 경우)가 가장 우선하며, 그다음은 실행 컨텍스트의 스레드 ID, 마지막은 codexTool({ threadId })입니다.
  • 실행 컨텍스트 키: name: 'codex'의 기본값은 codexThreadId이며, name: 'engineer' 같은 이름에는 codexThreadId_<suffix>가 사용됩니다(정규화 후 codex_engineer).
  • 변경 가능한 컨텍스트 요구 사항: useRunContextThreadId가 활성화된 경우 변경 가능한 객체 또는 Maprun(..., { context })로 전달합니다.
  • 이름 지정: 도구 이름은 codex 네임스페이스로 정규화되며(engineercodex_engineer가 됨), 에이전트에서 중복된 Codex 도구 이름은 거부됩니다.
  • 스트리밍: onStream은 Codex 이벤트(추론, 명령 실행, MCP 도구 호출, 파일 변경, 웹 검색)를 그대로 전달하므로 진행 상황을 로깅하거나 트레이싱할 수 있습니다.
  • 출력: 도구 결과에는 response, usage, threadId가 포함되며 Codex 토큰 사용량은 RunContext에 기록됩니다.
  • 구조: outputSchema는 설명자, JSON 스키마 객체 또는 Zod 객체일 수 있습니다. JSON 객체 스키마에서는 additionalPropertiesfalse여야 합니다.

실행 컨텍스트 스레드 재사용 예제:

Codex 실행 컨텍스트 스레드 재사용
import { Agent, run } from '@openai/agents';
import { codexTool } from '@openai/agents-extensions/experimental/codex';
// Derived from codexTool({ name: 'engineer' }) when runContextThreadIdKey is omitted.
type ExampleContext = {
codexThreadId_engineer?: string;
};
const agent = new Agent<ExampleContext>({
name: 'Codex assistant',
instructions: 'Use the codex tool for workspace tasks.',
tools: [
codexTool({
// `name` is optional for a single Codex tool.
// We set it so the run-context key is tool-specific and to avoid collisions when adding more Codex tools.
name: 'engineer',
// Reuse the same Codex thread across runs that share this context object.
useRunContextThreadId: true,
sandboxMode: 'workspace-write',
workingDirectory: '/path/to/repo',
defaultThreadOptions: {
model: 'gpt-5.4',
approvalPolicy: 'never',
},
}),
],
});
// The default key for useRunContextThreadId with name=engineer is codexThreadId_engineer.
const context: ExampleContext = {};
// First turn creates (or resumes) a Codex thread and stores the thread ID in context.
await run(agent, 'Inspect src/tool.ts and summarize it.', { context });
// Second turn reuses the same thread because it shares the same context object.
await run(agent, 'Now list refactoring opportunities.', { context });
const threadId = context.codexThreadId_engineer;

모델이 도구를 언제 어떻게 사용해야 하는지 제어하는 방법(modelSettings.toolChoice, toolUseBehavior 등)은 에이전트 가이드를 참고하세요.


  • 짧고 명확한 설명 – 도구가 무엇을 하고 언제 사용해야 하는지 설명합니다.
  • 입력 검증 – 가능한 경우 엄격한 JSON 검증을 위해 Zod 스키마를 사용합니다.
  • 오류 핸들러의 부작용 방지errorFunction은 예외를 발생시키는 대신 유용한 문자열을 반환해야 합니다.
  • 도구별 단일 책임 – 작고 조합 가능한 도구가 모델의 추론 성능을 높입니다.

  • 도구를 사용하는 에이전트를 정의하고 toolUseBehavior를 제어하는 방법은 에이전트를 참고하세요.
  • Agents as tools와 핸드오프 중 언제 무엇을 사용할지 결정하는 방법은 에이전트 오케스트레이션을 참고하세요.
  • 실행 흐름, 스트리밍, 대화 상태는 에이전트 실행을 참고하세요.
  • 호스티드 OpenAI 모델 설정과 Responses 전송 방식 선택은 모델을 참고하세요.
  • 도구 입력 또는 출력을 검증하는 방법은 가드레일을 참고하세요.
  • tool() 및 다양한 호스티드 툴 타입에 대한 TypeDoc 참조 문서를 자세히 살펴보세요.