@langchain/anthropic 1.2.3 → 1.3.0-dev-1765432861398

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +620 -3
  2. package/dist/chat_models.cjs +8 -5
  3. package/dist/chat_models.cjs.map +1 -1
  4. package/dist/chat_models.d.cts +13 -16
  5. package/dist/chat_models.d.cts.map +1 -0
  6. package/dist/chat_models.d.ts +13 -16
  7. package/dist/chat_models.d.ts.map +1 -0
  8. package/dist/chat_models.js +7 -4
  9. package/dist/chat_models.js.map +1 -1
  10. package/dist/index.cjs +3 -1
  11. package/dist/index.d.cts +12 -2
  12. package/dist/index.d.ts +12 -2
  13. package/dist/index.js +2 -1
  14. package/dist/tools/bash.cjs +95 -0
  15. package/dist/tools/bash.cjs.map +1 -0
  16. package/dist/tools/bash.d.cts +99 -0
  17. package/dist/tools/bash.d.cts.map +1 -0
  18. package/dist/tools/bash.d.ts +99 -0
  19. package/dist/tools/bash.d.ts.map +1 -0
  20. package/dist/tools/bash.js +94 -0
  21. package/dist/tools/bash.js.map +1 -0
  22. package/dist/tools/codeExecution.cjs +70 -0
  23. package/dist/tools/codeExecution.cjs.map +1 -0
  24. package/dist/tools/codeExecution.d.cts +75 -0
  25. package/dist/tools/codeExecution.d.cts.map +1 -0
  26. package/dist/tools/codeExecution.d.ts +75 -0
  27. package/dist/tools/codeExecution.d.ts.map +1 -0
  28. package/dist/tools/codeExecution.js +69 -0
  29. package/dist/tools/codeExecution.js.map +1 -0
  30. package/dist/tools/computer.cjs +161 -0
  31. package/dist/tools/computer.cjs.map +1 -0
  32. package/dist/tools/computer.d.cts +289 -0
  33. package/dist/tools/computer.d.cts.map +1 -0
  34. package/dist/tools/computer.d.ts +289 -0
  35. package/dist/tools/computer.d.ts.map +1 -0
  36. package/dist/tools/computer.js +159 -0
  37. package/dist/tools/computer.js.map +1 -0
  38. package/dist/tools/index.cjs +28 -0
  39. package/dist/tools/index.cjs.map +1 -0
  40. package/dist/tools/index.d.cts +28 -0
  41. package/dist/tools/index.d.cts.map +1 -0
  42. package/dist/tools/index.d.ts +28 -0
  43. package/dist/tools/index.d.ts.map +1 -0
  44. package/dist/tools/index.js +28 -0
  45. package/dist/tools/index.js.map +1 -0
  46. package/dist/tools/mcpToolset.cjs +111 -0
  47. package/dist/tools/mcpToolset.cjs.map +1 -0
  48. package/dist/tools/mcpToolset.d.cts +141 -0
  49. package/dist/tools/mcpToolset.d.cts.map +1 -0
  50. package/dist/tools/mcpToolset.d.ts +141 -0
  51. package/dist/tools/mcpToolset.d.ts.map +1 -0
  52. package/dist/tools/mcpToolset.js +110 -0
  53. package/dist/tools/mcpToolset.js.map +1 -0
  54. package/dist/tools/memory.cjs +56 -0
  55. package/dist/tools/memory.cjs.map +1 -0
  56. package/dist/tools/memory.d.cts +92 -0
  57. package/dist/tools/memory.d.cts.map +1 -0
  58. package/dist/tools/memory.d.ts +92 -0
  59. package/dist/tools/memory.d.ts.map +1 -0
  60. package/dist/tools/memory.js +55 -0
  61. package/dist/tools/memory.js.map +1 -0
  62. package/dist/tools/textEditor.cjs +79 -0
  63. package/dist/tools/textEditor.cjs.map +1 -0
  64. package/dist/tools/textEditor.d.cts +114 -0
  65. package/dist/tools/textEditor.d.cts.map +1 -0
  66. package/dist/tools/textEditor.d.ts +114 -0
  67. package/dist/tools/textEditor.d.ts.map +1 -0
  68. package/dist/tools/textEditor.js +78 -0
  69. package/dist/tools/textEditor.js.map +1 -0
  70. package/dist/tools/toolSearch.cjs +110 -0
  71. package/dist/tools/toolSearch.cjs.map +1 -0
  72. package/dist/tools/toolSearch.d.cts +108 -0
  73. package/dist/tools/toolSearch.d.cts.map +1 -0
  74. package/dist/tools/toolSearch.d.ts +108 -0
  75. package/dist/tools/toolSearch.d.ts.map +1 -0
  76. package/dist/tools/toolSearch.js +108 -0
  77. package/dist/tools/toolSearch.js.map +1 -0
  78. package/dist/tools/types.cjs +204 -0
  79. package/dist/tools/types.cjs.map +1 -0
  80. package/dist/tools/types.d.cts +366 -0
  81. package/dist/tools/types.d.cts.map +1 -0
  82. package/dist/tools/types.d.ts +366 -0
  83. package/dist/tools/types.d.ts.map +1 -0
  84. package/dist/tools/types.js +199 -0
  85. package/dist/tools/types.js.map +1 -0
  86. package/dist/tools/webFetch.cjs +70 -0
  87. package/dist/tools/webFetch.cjs.map +1 -0
  88. package/dist/tools/webFetch.d.cts +96 -0
  89. package/dist/tools/webFetch.d.cts.map +1 -0
  90. package/dist/tools/webFetch.d.ts +96 -0
  91. package/dist/tools/webFetch.d.ts.map +1 -0
  92. package/dist/tools/webFetch.js +69 -0
  93. package/dist/tools/webFetch.js.map +1 -0
  94. package/dist/tools/webSearch.cjs +57 -0
  95. package/dist/tools/webSearch.cjs.map +1 -0
  96. package/dist/tools/webSearch.d.cts +84 -0
  97. package/dist/tools/webSearch.d.cts.map +1 -0
  98. package/dist/tools/webSearch.d.ts +84 -0
  99. package/dist/tools/webSearch.d.ts.map +1 -0
  100. package/dist/tools/webSearch.js +56 -0
  101. package/dist/tools/webSearch.js.map +1 -0
  102. package/dist/types.d.cts +2 -3
  103. package/dist/types.d.cts.map +1 -0
  104. package/dist/types.d.ts +2 -3
  105. package/dist/types.d.ts.map +1 -0
  106. package/dist/utils/prompts.d.cts.map +1 -0
  107. package/dist/utils/prompts.d.ts.map +1 -0
  108. package/dist/utils/tools.cjs +9 -2
  109. package/dist/utils/tools.cjs.map +1 -1
  110. package/dist/utils/tools.js +13 -6
  111. package/dist/utils/tools.js.map +1 -1
  112. package/package.json +8 -7
package/README.md CHANGED
@@ -75,6 +75,623 @@ const response = await model.stream({
75
75
  });
76
76
  ```
77
77
 
78
+ ## Tools
79
+
80
+ This package provides LangChain-compatible wrappers for Anthropic's built-in tools. These tools can be bound to `ChatAnthropic` using `bindTools()` or any [`ReactAgent`](https://docs.langchain.com/oss/javascript/langchain/agents).
81
+
82
+ ### Memory Tool
83
+
84
+ The memory tool (`memory_20250818`) enables Claude to store and retrieve information across conversations through a memory file directory. Claude can create, read, update, and delete files that persist between sessions, allowing it to build knowledge over time without keeping everything in the context window.
85
+
86
+ ```typescript
87
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
88
+
89
+ // Create a simple in-memory file store (or use your own persistence layer)
90
+ const files = new Map<string, string>();
91
+
92
+ const memory = tools.memory_20250818({
93
+ execute: async (command) => {
94
+ switch (command.command) {
95
+ case "view":
96
+ if (!command.path || command.path === "/") {
97
+ return Array.from(files.keys()).join("\n") || "Directory is empty.";
98
+ }
99
+ return (
100
+ files.get(command.path) ?? `Error: File not found: ${command.path}`
101
+ );
102
+ case "create":
103
+ files.set(command.path!, command.file_text ?? "");
104
+ return `Successfully created file: ${command.path}`;
105
+ case "str_replace":
106
+ const content = files.get(command.path!);
107
+ if (content && command.old_str) {
108
+ files.set(
109
+ command.path!,
110
+ content.replace(command.old_str, command.new_str ?? "")
111
+ );
112
+ }
113
+ return `Successfully replaced text in: ${command.path}`;
114
+ case "delete":
115
+ files.delete(command.path!);
116
+ return `Successfully deleted: ${command.path}`;
117
+ // Handle other commands: insert, rename
118
+ default:
119
+ return `Unknown command`;
120
+ }
121
+ },
122
+ });
123
+
124
+ const llm = new ChatAnthropic({
125
+ model: "claude-sonnet-4-5-20250929",
126
+ });
127
+
128
+ const llmWithMemory = llm.bindTools([memory]);
129
+
130
+ const response = await llmWithMemory.invoke(
131
+ "Remember that my favorite programming language is TypeScript"
132
+ );
133
+ ```
134
+
135
+ For more information, see [Anthropic's Memory Tool documentation](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/memory-tool).
136
+
137
+ ### Web Search Tool
138
+
139
+ The web search tool (`webSearch_20250305`) gives Claude direct access to real-time web content, allowing it to answer questions with up-to-date information beyond its knowledge cutoff. Claude automatically cites sources from search results as part of its answer.
140
+
141
+ ```typescript
142
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
143
+
144
+ const llm = new ChatAnthropic({
145
+ model: "claude-sonnet-4-5-20250929",
146
+ });
147
+
148
+ // Basic usage
149
+ const response = await llm.invoke("What is the weather in NYC?", {
150
+ tools: [tools.webSearch_20250305()],
151
+ });
152
+ ```
153
+
154
+ The web search tool supports several configuration options:
155
+
156
+ ```typescript
157
+ const response = await llm.invoke("Latest news about AI?", {
158
+ tools: [
159
+ tools.webSearch_20250305({
160
+ // Maximum number of times the tool can be used in the API request
161
+ maxUses: 5,
162
+ // Only include results from these domains
163
+ allowedDomains: ["reuters.com", "bbc.com"],
164
+ // Or block specific domains (cannot be used with allowedDomains)
165
+ // blockedDomains: ["example.com"],
166
+ // Provide user location for more relevant results
167
+ userLocation: {
168
+ type: "approximate",
169
+ city: "San Francisco",
170
+ region: "California",
171
+ country: "US",
172
+ timezone: "America/Los_Angeles",
173
+ },
174
+ }),
175
+ ],
176
+ });
177
+ ```
178
+
179
+ For more information, see [Anthropic's Web Search Tool documentation](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/web-search-tool).
180
+
181
+ ### Web Fetch Tool
182
+
183
+ The web fetch tool (`webFetch_20250910`) allows Claude to retrieve full content from specified web pages and PDF documents. Claude can only fetch URLs that have been explicitly provided by the user or that come from previous web search or web fetch results.
184
+
185
+ > **⚠️ Security Warning:** Enabling the web fetch tool in environments where Claude processes untrusted input alongside sensitive data poses data exfiltration risks. We recommend only using this tool in trusted environments or when handling non-sensitive data.
186
+
187
+ ```typescript
188
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
189
+
190
+ const llm = new ChatAnthropic({
191
+ model: "claude-sonnet-4-5-20250929",
192
+ });
193
+
194
+ // Basic usage - fetch content from a URL
195
+ const response = await llm.invoke(
196
+ "Please analyze the content at https://example.com/article",
197
+ { tools: [tools.webFetch_20250910()] }
198
+ );
199
+ ```
200
+
201
+ The web fetch tool supports several configuration options:
202
+
203
+ ```typescript
204
+ const response = await llm.invoke(
205
+ "Summarize this research paper: https://arxiv.org/abs/2024.12345",
206
+ {
207
+ tools: [
208
+ tools.webFetch_20250910({
209
+ // Maximum number of times the tool can be used in the API request
210
+ maxUses: 5,
211
+ // Only fetch from these domains
212
+ allowedDomains: ["arxiv.org", "example.com"],
213
+ // Or block specific domains (cannot be used with allowedDomains)
214
+ // blockedDomains: ["example.com"],
215
+ // Enable citations for fetched content (optional, unlike web search)
216
+ citations: { enabled: true },
217
+ // Maximum content length in tokens (helps control token usage)
218
+ maxContentTokens: 50000,
219
+ }),
220
+ ],
221
+ }
222
+ );
223
+ ```
224
+
225
+ You can combine web fetch with web search for comprehensive information gathering:
226
+
227
+ ```typescript
228
+ import { tools } from "@langchain/anthropic";
229
+
230
+ const response = await llm.invoke(
231
+ "Find recent articles about quantum computing and analyze the most relevant one",
232
+ {
233
+ tools: [
234
+ tools.webSearch_20250305({ maxUses: 3 }),
235
+ tools.webFetch_20250910({ maxUses: 5, citations: { enabled: true } }),
236
+ ],
237
+ }
238
+ );
239
+ ```
240
+
241
+ For more information, see [Anthropic's Web Fetch Tool documentation](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/web-fetch-tool).
242
+
243
+ ### Tool Search Tools
244
+
245
+ The tool search tools enable Claude to work with hundreds or thousands of tools by dynamically discovering and loading them on-demand. This is useful when you have a large number of tools but don't want to load them all into the context window at once.
246
+
247
+ There are two variants:
248
+
249
+ - **`toolSearchRegex_20251119`** - Claude constructs regex patterns (using Python's `re.search()` syntax) to search for tools
250
+ - **`toolSearchBM25_20251119`** - Claude uses natural language queries to search for tools using the BM25 algorithm
251
+
252
+ ```typescript
253
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
254
+ import { tool } from "langchain";
255
+ import { z } from "zod";
256
+
257
+ const llm = new ChatAnthropic({
258
+ model: "claude-sonnet-4-5-20250929",
259
+ });
260
+
261
+ // Create tools with defer_loading to make them discoverable via search
262
+ const getWeather = tool(
263
+ async (input: { location: string }) => {
264
+ return `Weather in ${input.location}: Sunny, 72°F`;
265
+ },
266
+ {
267
+ name: "get_weather",
268
+ description: "Get the weather at a specific location",
269
+ schema: z.object({
270
+ location: z.string(),
271
+ }),
272
+ extras: { defer_loading: true },
273
+ }
274
+ );
275
+
276
+ const getNews = tool(
277
+ async (input: { topic: string }) => {
278
+ return `Latest news about ${input.topic}...`;
279
+ },
280
+ {
281
+ name: "get_news",
282
+ description: "Get the latest news about a topic",
283
+ schema: z.object({
284
+ topic: z.string(),
285
+ }),
286
+ extras: { defer_loading: true },
287
+ }
288
+ );
289
+
290
+ // Claude will search and discover tools as needed
291
+ const response = await llm.invoke("What is the weather in San Francisco?", {
292
+ tools: [tools.toolSearchRegex_20251119(), getWeather, getNews],
293
+ });
294
+ ```
295
+
296
+ Using the BM25 variant for natural language search:
297
+
298
+ ```typescript
299
+ import { tools } from "@langchain/anthropic";
300
+
301
+ const response = await llm.invoke("What is the weather in San Francisco?", {
302
+ tools: [tools.toolSearchBM25_20251119(), getWeather, getNews],
303
+ });
304
+ ```
305
+
306
+ For more information, see [Anthropic's Tool Search documentation](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-search-tool).
307
+
308
+ ### Text Editor Tool
309
+
310
+ The text editor tool (`textEditor_20250728`) enables Claude to view and modify text files, helping debug, fix, and improve code or other text documents. Claude can directly interact with files, providing hands-on assistance rather than just suggesting changes.
311
+
312
+ Available commands:
313
+
314
+ - `view` - Examine file contents or list directory contents
315
+ - `str_replace` - Replace specific text in a file
316
+ - `create` - Create a new file with specified content
317
+ - `insert` - Insert text at a specific line number
318
+
319
+ ```typescript
320
+ import fs from "node:fs";
321
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
322
+
323
+ const llm = new ChatAnthropic({
324
+ model: "claude-sonnet-4-5-20250929",
325
+ });
326
+
327
+ const textEditor = tools.textEditor_20250728({
328
+ async execute(args) {
329
+ switch (args.command) {
330
+ case "view":
331
+ const content = fs.readFileSync(args.path, "utf-8");
332
+ // Return with line numbers for Claude to reference
333
+ return content
334
+ .split("\n")
335
+ .map((line, i) => `${i + 1}: ${line}`)
336
+ .join("\n");
337
+ case "str_replace":
338
+ let fileContent = fs.readFileSync(args.path, "utf-8");
339
+ fileContent = fileContent.replace(args.old_str, args.new_str);
340
+ fs.writeFileSync(args.path, fileContent);
341
+ return "Successfully replaced text.";
342
+ case "create":
343
+ fs.writeFileSync(args.path, args.file_text);
344
+ return `Successfully created file: ${args.path}`;
345
+ case "insert":
346
+ const lines = fs.readFileSync(args.path, "utf-8").split("\n");
347
+ lines.splice(args.insert_line, 0, args.new_str);
348
+ fs.writeFileSync(args.path, lines.join("\n"));
349
+ return `Successfully inserted text at line ${args.insert_line}`;
350
+ default:
351
+ return "Unknown command";
352
+ }
353
+ },
354
+ // Optional: limit file content length when viewing
355
+ maxCharacters: 10000,
356
+ });
357
+
358
+ const llmWithEditor = llm.bindTools([textEditor]);
359
+
360
+ const response = await llmWithEditor.invoke(
361
+ "There's a syntax error in my primes.py file. Can you help me fix it?"
362
+ );
363
+ ```
364
+
365
+ For more information, see [Anthropic's Text Editor Tool documentation](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool).
366
+
367
+ ### Computer Use Tool
368
+
369
+ The computer use tools enable Claude to interact with desktop environments through screenshot capture, mouse control, and keyboard input for autonomous desktop interaction.
370
+
371
+ > **⚠️ Security Warning:** Computer use is a beta feature with unique risks. Use a dedicated virtual machine or container with minimal privileges. Avoid giving access to sensitive data.
372
+
373
+ There are two variants:
374
+
375
+ - **`computer_20251124`** - For Claude Opus 4.5 (includes zoom capability)
376
+ - **`computer_20250124`** - For Claude 4 and Claude 3.7 models
377
+
378
+ Available actions:
379
+
380
+ - `screenshot` - Capture the current screen
381
+ - `left_click`, `right_click`, `middle_click` - Mouse clicks at coordinates
382
+ - `double_click`, `triple_click` - Multi-click actions
383
+ - `left_click_drag` - Click and drag operations
384
+ - `left_mouse_down`, `left_mouse_up` - Granular mouse control
385
+ - `scroll` - Scroll the screen
386
+ - `type` - Type text
387
+ - `key` - Press keyboard keys/shortcuts
388
+ - `mouse_move` - Move the cursor
389
+ - `hold_key` - Hold a key while performing other actions
390
+ - `wait` - Wait for a specified duration
391
+ - `zoom` - View specific screen regions at full resolution (Claude Opus 4.5 only)
392
+
393
+ ```typescript
394
+ import {
395
+ ChatAnthropic,
396
+ tools,
397
+ type Computer20250124Action,
398
+ } from "@langchain/anthropic";
399
+
400
+ const llm = new ChatAnthropic({
401
+ model: "claude-sonnet-4-5-20250929",
402
+ });
403
+
404
+ const computer = tools.computer_20250124({
405
+ // Required: specify display dimensions
406
+ displayWidthPx: 1024,
407
+ displayHeightPx: 768,
408
+ // Optional: X11 display number
409
+ displayNumber: 1,
410
+ execute: async (action: Computer20250124Action) => {
411
+ switch (action.action) {
412
+ case "screenshot":
413
+ // Capture and return base64-encoded screenshot
414
+ // ...
415
+ case "left_click":
416
+ // Click at the specified coordinates
417
+ // ...
418
+ // ...
419
+ }
420
+ },
421
+ });
422
+
423
+ const llmWithComputer = llm.bindTools([computer]);
424
+
425
+ const response = await llmWithComputer.invoke(
426
+ "Save a picture of a cat to my desktop."
427
+ );
428
+ ```
429
+
430
+ For Claude Opus 4.5 with zoom support:
431
+
432
+ ```typescript
433
+ import { tools } from "@langchain/anthropic";
434
+
435
+ const computer = tools.computer_20251124({
436
+ displayWidthPx: 1920,
437
+ displayHeightPx: 1080,
438
+ // Enable zoom for detailed screen region inspection
439
+ enableZoom: true,
440
+ execute: async (action) => {
441
+ // Handle actions including "zoom" for Claude Opus 4.5
442
+ // ...
443
+ },
444
+ });
445
+ ```
446
+
447
+ For more information, see [Anthropic's Computer Use documentation](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/computer-use).
448
+
449
+ ### Code Execution Tool
450
+
451
+ The code execution tool (`codeExecution_20250825`) allows Claude to run Bash commands and manipulate files in a secure, sandboxed environment. Claude can analyze data, create visualizations, perform calculations, and process files.
452
+
453
+ When this tool is provided, Claude automatically gains access to:
454
+
455
+ - **Bash commands** - Execute shell commands for system operations
456
+ - **File operations** - Create, view, and edit files directly
457
+
458
+ ```typescript
459
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
460
+
461
+ const llm = new ChatAnthropic({
462
+ model: "claude-sonnet-4-5-20250929",
463
+ });
464
+
465
+ // Basic usage - calculations and data analysis
466
+ const response = await llm.invoke(
467
+ "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
468
+ { tools: [tools.codeExecution_20250825()] }
469
+ );
470
+
471
+ // File operations and visualization
472
+ const response2 = await llm.invoke(
473
+ "Create a matplotlib visualization of sales data and save it as chart.png",
474
+ { tools: [tools.codeExecution_20250825()] }
475
+ );
476
+ ```
477
+
478
+ Container reuse for multi-step workflows:
479
+
480
+ ```typescript
481
+ // First request - creates a container
482
+ const response1 = await llm.invoke("Write a random number to /tmp/number.txt", {
483
+ tools: [tools.codeExecution_20250825()],
484
+ });
485
+
486
+ // Extract container ID from response for reuse
487
+ const containerId = response1.response_metadata?.container?.id;
488
+
489
+ // Second request - reuse container to access the file
490
+ const response2 = await llm.invoke(
491
+ "Read /tmp/number.txt and calculate its square",
492
+ {
493
+ tools: [tools.codeExecution_20250825()],
494
+ container: containerId,
495
+ }
496
+ );
497
+ ```
498
+
499
+ For more information, see [Anthropic's Code Execution Tool documentation](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/code-execution-tool).
500
+
501
+ ### Bash Tool
502
+
503
+ The bash tool (`bash_20250124`) enables shell command execution in a persistent bash session. Unlike the sandboxed code execution tool, this tool requires you to provide your own execution environment.
504
+
505
+ > **⚠️ Security Warning:** The bash tool provides direct system access. Implement safety measures such as running in isolated environments (Docker/VM), command filtering, and resource limits.
506
+
507
+ The bash tool provides:
508
+
509
+ - **Persistent bash session** - Maintains state between commands
510
+ - **Shell command execution** - Run any shell command
511
+ - **Environment access** - Access to environment variables and working directory
512
+ - **Command chaining** - Support for pipes, redirects, and scripting
513
+
514
+ Available commands:
515
+
516
+ - Execute a command: `{ command: "ls -la" }`
517
+ - Restart the session: `{ restart: true }`
518
+
519
+ ```typescript
520
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
521
+ import { execSync } from "child_process";
522
+
523
+ const llm = new ChatAnthropic({
524
+ model: "claude-sonnet-4-5-20250929",
525
+ });
526
+
527
+ const bash = tools.bash_20250124({
528
+ execute: async (args) => {
529
+ if (args.restart) {
530
+ // Reset session state
531
+ return "Bash session restarted";
532
+ }
533
+ try {
534
+ const output = execSync(args.command, {
535
+ encoding: "utf-8",
536
+ timeout: 30000,
537
+ });
538
+ return output;
539
+ } catch (error) {
540
+ return `Error: ${(error as Error).message}`;
541
+ }
542
+ },
543
+ });
544
+
545
+ const llmWithBash = llm.bindTools([bash]);
546
+
547
+ const response = await llmWithBash.invoke(
548
+ "List all Python files in the current directory"
549
+ );
550
+
551
+ // Process tool calls and execute commands
552
+ console.log(response.tool_calls?.[0].name); // "bash"
553
+ console.log(response.tool_calls?.[0].args.command); // "ls -la *.py"
554
+ ```
555
+
556
+ For more information, see [Anthropic's Bash Tool documentation](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/bash-tool).
557
+
558
+ ### MCP Toolset
559
+
560
+ The MCP toolset (`mcpToolset_20251120`) enables Claude to connect to remote MCP (Model Context Protocol) servers directly from the Messages API without implementing a separate MCP client. This allows Claude to use tools provided by MCP servers.
561
+
562
+ Key features:
563
+
564
+ - **Direct API integration** - Connect to MCP servers without implementing an MCP client
565
+ - **Tool calling support** - Access MCP tools through the Messages API
566
+ - **Flexible tool configuration** - Enable all tools, allowlist specific tools, or denylist unwanted tools
567
+ - **Per-tool configuration** - Configure individual tools with custom settings
568
+ - **OAuth authentication** - Support for OAuth Bearer tokens for authenticated servers
569
+ - **Multiple servers** - Connect to multiple MCP servers in a single request
570
+
571
+ ```typescript
572
+ import { ChatAnthropic, tools } from "@langchain/anthropic";
573
+
574
+ const llm = new ChatAnthropic({
575
+ model: "claude-sonnet-4-5-20250929",
576
+ });
577
+
578
+ // Basic usage - enable all tools from an MCP server
579
+ const response = await llm.invoke("What tools do you have available?", {
580
+ mcp_servers: [
581
+ {
582
+ type: "url",
583
+ url: "https://example-server.modelcontextprotocol.io/sse",
584
+ name: "example-mcp",
585
+ authorization_token: "YOUR_TOKEN",
586
+ },
587
+ ],
588
+ tools: [tools.mcpToolset_20251120({ serverName: "example-mcp" })],
589
+ });
590
+ ```
591
+
592
+ **Allowlist pattern** - Enable only specific tools:
593
+
594
+ ```typescript
595
+ const response = await llm.invoke("Search for events", {
596
+ mcp_servers: [
597
+ {
598
+ type: "url",
599
+ url: "https://calendar.example.com/sse",
600
+ name: "google-calendar-mcp",
601
+ authorization_token: "YOUR_TOKEN",
602
+ },
603
+ ],
604
+ tools: [
605
+ tools.mcpToolset_20251120({
606
+ serverName: "google-calendar-mcp",
607
+ // Disable all tools by default
608
+ defaultConfig: { enabled: false },
609
+ // Explicitly enable only these tools
610
+ configs: {
611
+ search_events: { enabled: true },
612
+ create_event: { enabled: true },
613
+ },
614
+ }),
615
+ ],
616
+ });
617
+ ```
618
+
619
+ **Denylist pattern** - Disable specific tools:
620
+
621
+ ```typescript
622
+ const response = await llm.invoke("List my events", {
623
+ mcp_servers: [
624
+ {
625
+ type: "url",
626
+ url: "https://calendar.example.com/sse",
627
+ name: "google-calendar-mcp",
628
+ authorization_token: "YOUR_TOKEN",
629
+ },
630
+ ],
631
+ tools: [
632
+ tools.mcpToolset_20251120({
633
+ serverName: "google-calendar-mcp",
634
+ // All tools enabled by default, just disable dangerous ones
635
+ configs: {
636
+ delete_all_events: { enabled: false },
637
+ share_calendar_publicly: { enabled: false },
638
+ },
639
+ }),
640
+ ],
641
+ });
642
+ ```
643
+
644
+ **Multiple MCP servers**:
645
+
646
+ ```typescript
647
+ const response = await llm.invoke("Use tools from both servers", {
648
+ mcp_servers: [
649
+ {
650
+ type: "url",
651
+ url: "https://mcp.example1.com/sse",
652
+ name: "mcp-server-1",
653
+ authorization_token: "TOKEN1",
654
+ },
655
+ {
656
+ type: "url",
657
+ url: "https://mcp.example2.com/sse",
658
+ name: "mcp-server-2",
659
+ authorization_token: "TOKEN2",
660
+ },
661
+ ],
662
+ tools: [
663
+ tools.mcpToolset_20251120({ serverName: "mcp-server-1" }),
664
+ tools.mcpToolset_20251120({
665
+ serverName: "mcp-server-2",
666
+ defaultConfig: { deferLoading: true },
667
+ }),
668
+ ],
669
+ });
670
+ ```
671
+
672
+ **With Tool Search** - Use deferred loading for on-demand tool discovery:
673
+
674
+ ```typescript
675
+ const response = await llm.invoke("Find and use the right tool", {
676
+ mcp_servers: [
677
+ {
678
+ type: "url",
679
+ url: "https://example.com/sse",
680
+ name: "example-mcp",
681
+ },
682
+ ],
683
+ tools: [
684
+ tools.toolSearchRegex_20251119(),
685
+ tools.mcpToolset_20251120({
686
+ serverName: "example-mcp",
687
+ defaultConfig: { deferLoading: true },
688
+ }),
689
+ ],
690
+ });
691
+ ```
692
+
693
+ For more information, see [Anthropic's MCP Connector documentation](https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector).
694
+
78
695
  ## Development
79
696
 
80
697
  To develop the Anthropic package, you'll need to follow these instructions:
@@ -103,8 +720,8 @@ Test files should live within a `tests/` file in the `src/` folder. Unit tests s
103
720
  end in `.int.test.ts`:
104
721
 
105
722
  ```bash
106
- $ pnpm test
107
- $ pnpm test:int
723
+ pnpm test
724
+ pnpm test:int
108
725
  ```
109
726
 
110
727
  ### Lint & Format
@@ -124,5 +741,5 @@ If you add a new file to be exported, either import & re-export from `src/index.
124
741
  After running `pnpm build`, publish a new version with:
125
742
 
126
743
  ```bash
127
- $ npm publish
744
+ npm publish
128
745
  ```
@@ -6,7 +6,7 @@ const require_message_outputs = require('./utils/message_outputs.cjs');
6
6
  const require_errors = require('./utils/errors.cjs');
7
7
  const require_profiles = require('./profiles.cjs');
8
8
  const __anthropic_ai_sdk = require_rolldown_runtime.__toESM(require("@anthropic-ai/sdk"));
9
- const __anthropic_ai_sdk_lib_transform_json_schema_js = require_rolldown_runtime.__toESM(require("@anthropic-ai/sdk/lib/transform-json-schema.js"));
9
+ const __anthropic_ai_sdk_lib_transform_json_schema = require_rolldown_runtime.__toESM(require("@anthropic-ai/sdk/lib/transform-json-schema"));
10
10
  const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
11
11
  const __langchain_core_outputs = require_rolldown_runtime.__toESM(require("@langchain/core/outputs"));
12
12
  const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
@@ -61,9 +61,10 @@ function isBuiltinTool(tool) {
61
61
  "str_replace_based_edit_tool_",
62
62
  "code_execution_",
63
63
  "memory_",
64
- "tool_search_"
64
+ "tool_search_",
65
+ "mcp_toolset"
65
66
  ];
66
- return typeof tool === "object" && tool !== null && "type" in tool && "name" in tool && typeof tool.type === "string" && builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix));
67
+ return typeof tool === "object" && tool !== null && "type" in tool && ("name" in tool || "mcp_server_name" in tool) && typeof tool.type === "string" && builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix));
67
68
  }
68
69
  function _combineBetas(a, b, ...rest) {
69
70
  return Array.from(new Set([
@@ -677,6 +678,7 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
677
678
  formatStructuredToolToAnthropic(tools) {
678
679
  if (!tools || !tools.length) return void 0;
679
680
  return tools.map((tool) => {
681
+ if ((0, __langchain_core_utils_function_calling.isLangChainTool)(tool) && tool.extras?.providerToolDefinition) return tool.extras.providerToolDefinition;
680
682
  if (isBuiltinTool(tool)) return tool;
681
683
  if (isAnthropicTool(tool)) return tool;
682
684
  if ((0, __langchain_core_language_models_base.isOpenAITool)(tool)) return {
@@ -723,7 +725,8 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
723
725
  ...this.invocationKwargs,
724
726
  container: options?.container,
725
727
  betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []),
726
- output_format: options?.output_format
728
+ output_format: options?.output_format,
729
+ mcp_servers: options?.mcp_servers
727
730
  };
728
731
  if (this.thinking.type === "enabled") {
729
732
  if (this.topP !== void 0 && this.topK !== -1) throw new Error("topK is not supported when thinking is enabled");
@@ -935,7 +938,7 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
935
938
  }
936
939
  if (method === "jsonSchema") {
937
940
  outputParser = (0, __langchain_core_utils_types.isInteropZodSchema)(schema) ? __langchain_core_output_parsers.StructuredOutputParser.fromZodSchema(schema) : new __langchain_core_output_parsers.JsonOutputParser();
938
- const jsonSchema = (0, __anthropic_ai_sdk_lib_transform_json_schema_js.transformJSONSchema)((0, __langchain_core_utils_json_schema.toJsonSchema)(schema));
941
+ const jsonSchema = (0, __anthropic_ai_sdk_lib_transform_json_schema.transformJSONSchema)((0, __langchain_core_utils_json_schema.toJsonSchema)(schema));
939
942
  llm = this.withConfig({
940
943
  outputVersion: "v0",
941
944
  output_format: {