Anthropic 통합

Anthropic 통합

LangChain JavaScript로 Anthropic 도구와 통합하는 방법을 알아봅니다.

@langchain/anthropic 패키지는 Anthropic의 내장 도구에 대한 LangChain 호환 래퍼를 제공해요. 이러한 도구는 bindTools() 또는 createAgent를 사용해 ChatAnthropic에 바인딩할 수 있습니다.

출처: 문서

본문

메모리 도구(Memory tool)

메모리 도구(memory_20250818)는 Claude가 메모리 파일 디렉터리를 통해 대화 간에 정보를 저장하고 검색할 수 있게 합니다. Claude는 세션 간에 지속되는 파일을 생성, 읽기, 업데이트, 삭제할 수 있어 모든 것을 컨텍스트 창에 유지하지 않고도 시간이 지나면서 지식을 쌓을 수 있습니다.

import { ChatAnthropic, tools } from "@langchain/anthropic";

// Create a simple in-memory file store (or use your own persistence layer)
const files = new Map<string, string>();

const memory = tools.memory_20250818({
  execute: async (command) => {
    switch (command.command) {
      case "view":
        if (!command.path || command.path === "/") {
          return Array.from(files.keys()).join("\n") || "Directory is empty.";
        }
        return (
          files.get(command.path) ?? `Error: File not found: ${command.path}`
        );
      case "create":
        files.set(command.path!, command.file_text ?? "");
        return `Successfully created file: ${command.path}`;
      case "str_replace":
        const content = files.get(command.path!);
        if (content && command.old_str) {
          files.set(
            command.path!,
            content.replace(command.old_str, command.new_str ?? "")
          );
        }
        return `Successfully replaced text in: ${command.path}`;
      case "delete":
        files.delete(command.path!);
        return `Successfully deleted: ${command.path}`;
      // Handle other commands: insert, rename
      default:
        return `Unknown command`;
    }
  },
});

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

const llmWithMemory = llm.bindTools([memory]);

const response = await llmWithMemory.invoke(
  "Remember that my favorite programming language is TypeScript"
);

자세한 내용은 Anthropic의 Memory Tool 문서를 참조하세요.

웹 검색 도구(Web search tool)

웹 검색 도구(webSearch_20250305)는 Claude에게 실시간 웹 콘텐츠에 대한 직접 접근을 제공하며, 지식 학습 시점(knowledge cutoff)을 넘어 최신 정보로 질문에 답할 수 있게 합니다. Claude는 답변의 일부로 검색 결과의 출처를 자동으로 인용합니다.

import { ChatAnthropic, tools } from "@langchain/anthropic";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

// Basic usage
const response = await llm.invoke("What is the weather in NYC?", {
  tools: [tools.webSearch_20250305()],
});

웹 검색 도구는 몇 가지 구성 옵션을 지원합니다:

const response = await llm.invoke("Latest news about AI?", {
  tools: [
    tools.webSearch_20250305({
      // Maximum number of times the tool can be used in the API request
      maxUses: 5,
      // Only include results from these domains
      allowedDomains: ["reuters.com", "bbc.com"],
      // Or block specific domains (cannot be used with allowedDomains)
      // blockedDomains: ["example.com"],
      // Provide user location for more relevant results
      userLocation: {
        type: "approximate",
        city: "San Francisco",
        region: "California",
        country: "US",
        timezone: "America/Los_Angeles",
      },
    }),
  ],
});

자세한 내용은 Anthropic의 Web Search Tool 문서를 참조하세요.

웹 가져오기 도구(Web fetch tool)

웹 가져오기 도구(webFetch_20250910)는 Claude가 지정된 웹 페이지와 PDF 문서에서 전체 콘텐츠를 가져올 수 있게 합니다. Claude는 사용자가 명시적으로 제공했거나 이전 웹 검색·웹 가져오기 결과에서 온 URL만 가져올 수 있습니다.

⚠️ 보안 경고: Claude가 신뢰할 수 없는 입력과 민감한 데이터를 함께 처리하는 환경에서 웹 가져오기 도구를 활성화하면 데이터 유출 위험이 있습니다. 신뢰할 수 있는 환경 또는 비민감 데이터를 다룰 때만 이 도구를 사용하는 것을 권장합니다.

import { ChatAnthropic, tools } from "@langchain/anthropic";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

// Basic usage - fetch content from a URL
const response = await llm.invoke(
  "Please analyze the content at https://example.com/article",
  { tools: [tools.webFetch_20250910()] }
);

웹 가져오기 도구는 몇 가지 구성 옵션을 지원합니다:

const response = await llm.invoke(
  "Summarize this research paper: https://arxiv.org/abs/2024.12345",
  {
    tools: [
      tools.webFetch_20250910({
        // Maximum number of times the tool can be used in the API request
        maxUses: 5,
        // Only fetch from these domains
        allowedDomains: ["arxiv.org", "example.com"],
        // Or block specific domains (cannot be used with allowedDomains)
        // blockedDomains: ["example.com"],
        // Enable citations for fetched content (optional, unlike web search)
        citations: { enabled: true },
        // Maximum content length in tokens (helps control token usage)
        maxContentTokens: 50000,
      }),
    ],
  }
);

웹 가져오기와 웹 검색을 결합해 포괄적인 정보 수집을 수행할 수 있습니다:

import { tools } from "@langchain/anthropic";

const response = await llm.invoke(
  "Find recent articles about quantum computing and analyze the most relevant one",
  {
    tools: [
      tools.webSearch_20250305({ maxUses: 3 }),
      tools.webFetch_20250910({ maxUses: 5, citations: { enabled: true } }),
    ],
  }
);

자세한 내용은 Anthropic의 Web Fetch Tool 문서를 참조하세요.

도구 검색 도구(Tool search tools)

도구 검색 도구는 Claude가 수백 또는 수천 개의 도구로 작업할 수 있게 하며, 도구를 필요에 따라 동적으로 발견하고 로드합니다. 이는 도구가 많지만 모두 한 번에 컨텍스트 창에 로드하고 싶지 않을 때 유용합니다.

두 가지 변형이 있습니다:

  • toolSearchRegex_20251119 - Claude가 도구를 검색하기 위해 정규식 패턴(Python의 re.search() 구문 사용)을 구성
  • toolSearchBM25_20251119 - Claude가 BM25 알고리즘을 사용해 자연어 질의로 도구를 검색
import { ChatAnthropic, tools } from "@langchain/anthropic";
import { tool } from "langchain";
import { z } from "zod";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

// Create tools with defer_loading to make them discoverable via search
const getWeather = tool(
  async (input: { location: string }) => {
    return `Weather in ${input.location}: Sunny, 72°F`;
  },
  {
    name: "get_weather",
    description: "Get the weather at a specific location",
    schema: z.object({
      location: z.string(),
    }),
    extras: { defer_loading: true },
  }
);

const getNews = tool(
  async (input: { topic: string }) => {
    return `Latest news about ${input.topic}...`;
  },
  {
    name: "get_news",
    description: "Get the latest news about a topic",
    schema: z.object({
      topic: z.string(),
    }),
    extras: { defer_loading: true },
  }
);

// Claude will search and discover tools as needed
const response = await llm.invoke("What is the weather in San Francisco?", {
  tools: [tools.toolSearchRegex_20251119(), getWeather, getNews],
});

자연어 검색을 위한 BM25 변형 사용:

import { tools } from "@langchain/anthropic";

const response = await llm.invoke("What is the weather in San Francisco?", {
  tools: [tools.toolSearchBM25_20251119(), getWeather, getNews],
});

자세한 내용은 Anthropic의 Tool Search 문서를 참조하세요.

텍스트 편집기 도구(Text editor tool)

텍스트 편집기 도구(textEditor_20250728)는 Claude가 텍스트 파일을 보고 수정할 수 있게 하여 코드나 기타 텍스트 문서를 디버깅, 수정, 개선하는 데 도움을 줍니다. Claude는 변경만 제안하는 것이 아니라 파일과 직접 상호작용하여 실질적인 도움을 제공할 수 있습니다.

사용 가능한 명령:

  • view - 파일 내용 검사 또는 디렉터리 내용 나열
  • str_replace - 파일에서 특정 텍스트 교체
  • create - 지정된 콘텐츠로 새 파일 생성
  • insert - 특정 줄 번호에 텍스트 삽입
import fs from "node:fs";
import { ChatAnthropic, tools } from "@langchain/anthropic";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

const textEditor = tools.textEditor_20250728({
  async execute(args) {
    switch (args.command) {
      case "view":
        const content = fs.readFileSync(args.path, "utf-8");
        // Return with line numbers for Claude to reference
        return content
          .split("\n")
          .map((line, i) => `${i + 1}: ${line}`)
          .join("\n");
      case "str_replace":
        let fileContent = fs.readFileSync(args.path, "utf-8");
        fileContent = fileContent.replace(args.old_str, args.new_str);
        fs.writeFileSync(args.path, fileContent);
        return "Successfully replaced text.";
      case "create":
        fs.writeFileSync(args.path, args.file_text);
        return `Successfully created file: ${args.path}`;
      case "insert":
        const lines = fs.readFileSync(args.path, "utf-8").split("\n");
        lines.splice(args.insert_line, 0, args.new_str);
        fs.writeFileSync(args.path, lines.join("\n"));
        return `Successfully inserted text at line ${args.insert_line}`;
      default:
        return "Unknown command";
    }
  },
  // Optional: limit file content length when viewing
  maxCharacters: 10000,
});

const llmWithEditor = llm.bindTools([textEditor]);

const response = await llmWithEditor.invoke(
  "There's a syntax error in my primes.py file. Can you help me fix it?"
);

자세한 내용은 Anthropic의 Text Editor Tool 문서를 참조하세요.

컴퓨터 사용 도구(Computer use tool)

컴퓨터 사용 도구는 Claude가 스크린샷 캡처, 마우스 제어, 키보드 입력을 통해 데스크톱 환경과 상호작용하여 자율적인 데스크톱 상호작용을 수행할 수 있게 합니다.

⚠️ 보안 경고: 컴퓨터 사용은 고유한 위험이 있는 베타 기능입니다. 최소 권한의 전용 가상 머신이나 컨테이너를 사용하세요. 민감한 데이터에 접근하지 않도록 하세요.

두 가지 변형이 있습니다:

  • computer_20251124 - Claude Opus 4.5용(줌 기능 포함)
  • computer_20250124 - Claude 4 및 Claude 3.7 모델용

사용 가능한 동작:

  • screenshot - 현재 화면 캡처
  • left_click, right_click, middle_click - 좌표에서 마우스 클릭
  • double_click, triple_click - 다중 클릭 동작
  • left_click_drag - 클릭 및 드래그 작업
  • left_mouse_down, left_mouse_up - 세밀한 마우스 제어
  • scroll - 화면 스크롤
  • type - 텍스트 입력
  • key - 키보드 키/단축키 누르기
  • mouse_move - 커서 이동
  • hold_key - 다른 동작 수행 중 키를 누르고 있기
  • wait - 지정된 시간 대기
  • zoom - 전체 해상도로 특정 화면 영역 보기(Claude Opus 4.5 전용)
import { ChatAnthropic, tools } from "@langchain/anthropic";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

const computer = tools.computer_20250124({
  // Required: specify display dimensions
  displayWidthPx: 1024,
  displayHeightPx: 768,
  // Optional: X11 display number
  displayNumber: 1,
  execute: async (action) => {
    switch (action.action) {
      case "screenshot":
      // Capture and return base64-encoded screenshot
      // ...
      case "left_click":
      // Click at the specified coordinates
      // ...
      // ...
    }
  },
});

const llmWithComputer = llm.bindTools([computer]);

const response = await llmWithComputer.invoke(
  "Save a picture of a cat to my desktop."
);

줌 지원이 있는 Claude Opus 4.5용:

import { tools } from "@langchain/anthropic";

const computer = tools.computer_20251124({
  displayWidthPx: 1920,
  displayHeightPx: 1080,
  // Enable zoom for detailed screen region inspection
  enableZoom: true,
  execute: async (action) => {
    // Handle actions including "zoom" for Claude Opus 4.5
    // ...
  },
});

자세한 내용은 Anthropic의 Computer Use 문서를 참조하세요.

코드 실행 도구(Code execution tool)

코드 실행 도구(codeExecution_20250825)는 Claude가 안전하고 샌드박싱된 환경에서 Bash 명령을 실행하고 파일을 조작할 수 있게 합니다. Claude는 데이터를 분석하고, 시각화를 만들고, 계산을 수행하고, 파일을 처리할 수 있습니다.

이 도구가 제공되면 Claude는 자동으로 다음에 접근할 수 있습니다:

  • Bash 명령 - 시스템 작업을 위한 셸 명령 실행
  • 파일 작업 - 파일 직접 생성, 보기, 편집
import { ChatAnthropic, tools } from "@langchain/anthropic";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

// Basic usage - calculations and data analysis
const response = await llm.invoke(
  "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
  { tools: [tools.codeExecution_20250825()] }
);

// File operations and visualization
const response2 = await llm.invoke(
  "Create a matplotlib visualization of sales data and save it as chart.png",
  { tools: [tools.codeExecution_20250825()] }
);

다단계 워크플로를 위한 컨테이너 재사용:

// First request - creates a container
const response1 = await llm.invoke("Write a random number to /tmp/number.txt", {
  tools: [tools.codeExecution_20250825()],
});

// Extract container ID from response for reuse
const containerId = response1.response_metadata?.container?.id;

// Second request - reuse container to access the file
const response2 = await llm.invoke(
  "Read /tmp/number.txt and calculate its square",
  {
    tools: [tools.codeExecution_20250825()],
    container: containerId,
  }
);

자세한 내용은 Anthropic의 Code Execution Tool 문서를 참조하세요.

Bash 도구(Bash tool)

bash 도구(bash_20250124)는 영속적인 bash 세션에서 셸 명령 실행을 가능하게 합니다. 샌드박싱된 코드 실행 도구와 달리, 이 도구는 자체 실행 환경을 제공해야 합니다.

⚠️ 보안 경고: bash 도구는 시스템에 직접 접근을 제공합니다. 격리된 환경(Docker/VM)에서 실행, 명령 필터링, 리소스 제한 같은 안전 조치를 구현하세요.

bash 도구는 다음을 제공합니다:

  • 영속적 bash 세션 - 명령 간 상태 유지
  • 셸 명령 실행 - 모든 셸 명령 실행
  • 환경 접근 - 환경 변수와 작업 디렉터리에 접근
  • 명령 체이닝 - 파이프, 리다이렉트, 스크립팅 지원

사용 가능한 명령:

  • 명령 실행: { command: "ls -la" }
  • 세션 재시작: { restart: true }
import { ChatAnthropic, tools } from "@langchain/anthropic";
import { execSync } from "child_process";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

const bash = tools.bash_20250124({
  execute: async (args) => {
    if (args.restart) {
      // Reset session state
      return "Bash session restarted";
    }
    try {
      const output = execSync(args.command, {
        encoding: "utf-8",
        timeout: 30000,
      });
      return output;
    } catch (error) {
      return `Error: ${(error as Error).message}`;
    }
  },
});

const llmWithBash = llm.bindTools([bash]);

const response = await llmWithBash.invoke(
  "List all Python files in the current directory"
);

// Process tool calls and execute commands
console.log(response.tool_calls?.[0].name); // "bash"
console.log(response.tool_calls?.[0].args.command); // "ls -la *.py"

자세한 내용은 Anthropic의 Bash Tool 문서를 참조하세요.

MCP 툴셋(MCP toolset)

MCP 툴셋(mcpToolset_20251120)은 Claude가 별도의 MCP 클라이언트를 구현하지 않고도 Messages API에서 직접 원격 MCP(Model Context Protocol) 서버에 연결할 수 있게 합니다. 이를 통해 Claude는 MCP 서버가 제공하는 도구를 사용할 수 있습니다.

주요 기능:

  • 직접 API 통합 - MCP 클라이언트를 구현하지 않고 MCP 서버에 연결
  • 도구 호출 지원 - Messages API를 통해 MCP 도구에 접근
  • 유연한 도구 구성 - 모든 도구 활성화, 특정 도구 허용 목록, 원치 않는 도구 거부 목록
  • 도구별 구성 - 커스텀 설정으로 개별 도구 구성
  • OAuth 인증 - 인증된 서버를 위한 OAuth Bearer 토큰 지원
  • 다중 서버 - 단일 요청에서 여러 MCP 서버에 연결
import { ChatAnthropic, tools } from "@langchain/anthropic";

const llm = new ChatAnthropic({
  model: "claude-sonnet-4-6",
});

// Basic usage - enable all tools from an MCP server
const response = await llm.invoke("What tools do you have available?", {
  mcp_servers: [
    {
      type: "url",
      url: "https://example-server.modelcontextprotocol.io/sse",
      name: "example-mcp",
      authorization_token: "YOUR_TOKEN",
    },
  ],
  tools: [tools.mcpToolset_20251120({ serverName: "example-mcp" })],
});

허용 목록 패턴(Allowlist pattern) - 특정 도구만 활성화:

const response = await llm.invoke("Search for events", {
  mcp_servers: [
    {
      type: "url",
      url: "https://calendar.example.com/sse",
      name: "google-calendar-mcp",
      authorization_token: "YOUR_TOKEN",
    },
  ],
  tools: [
    tools.mcpToolset_20251120({
      serverName: "google-calendar-mcp",
      // Disable all tools by default
      defaultConfig: { enabled: false },
      // Explicitly enable only these tools
      configs: {
        search_events: { enabled: true },
        create_event: { enabled: true },
      },
    }),
  ],
});

거부 목록 패턴(Denylist pattern) - 특정 도구 비활성화:

const response = await llm.invoke("List my events", {
  mcp_servers: [
    {
      type: "url",
      url: "https://calendar.example.com/sse",
      name: "google-calendar-mcp",
      authorization_token: "YOUR_TOKEN",
    },
  ],
  tools: [
    tools.mcpToolset_20251120({
      serverName: "google-calendar-mcp",
      // All tools enabled by default, just disable dangerous ones
      configs: {
        delete_all_events: { enabled: false },
        share_calendar_publicly: { enabled: false },
      },
    }),
  ],
});

다중 MCP 서버(Multiple MCP servers):

const response = await llm.invoke("Use tools from both servers", {
  mcp_servers: [
    {
      type: "url",
      url: "https://mcp.example1.com/sse",
      name: "mcp-server-1",
      authorization_token: "TOKEN1",
    },
    {
      type: "url",
      url: "https://mcp.example2.com/sse",
      name: "mcp-server-2",
      authorization_token: "TOKEN2",
    },
  ],
  tools: [
    tools.mcpToolset_20251120({ serverName: "mcp-server-1" }),
    tools.mcpToolset_20251120({
      serverName: "mcp-server-2",
      defaultConfig: { deferLoading: true },
    }),
  ],
});

도구 검색과 함께(Tool Search 사용) - 요청 시 도구 발견을 위해 지연 로딩 사용:

const response = await llm.invoke("Find and use the right tool", {
  mcp_servers: [
    {
      type: "url",
      url: "https://example.com/sse",
      name: "example-mcp",
    },
  ],
  tools: [
    tools.toolSearchRegex_20251119(),
    tools.mcpToolset_20251120({
      serverName: "example-mcp",
      defaultConfig: { deferLoading: true },
    }),
  ],
});

자세한 내용은 Anthropic의 MCP Connector 문서를 참조하세요.

더 알아보기 (Learn more)