Debian Codegraph @

src/anthropic/lib/tools/mcp.py

raw
1 """Helpers for integrating MCP (Model Context Protocol) SDK types with the Anthropic SDK.
2
3 These helpers reduce boilerplate when converting between MCP types and Anthropic API types.
4
5 Usage:
6
7 ```py
8 from anthropic.lib.tools.mcp import mcp_tool, async_mcp_tool, mcp_message
9 ```
10
11 This module requires the `mcp` package to be installed.
12 """
13 # pyright: reportUnknownArgumentType=false, reportUnknownMemberType=false, reportUnknownVariableType=false, reportMissingImports=false, reportUnknownParameterType=false
14
15 from __future__ import annotations
16
17 import json
18 import base64
19 from typing import Any, Iterable
20 from urllib.parse import urlparse
21 from typing_extensions import Literal
22
23 try:
24 from mcp.types import ( # type: ignore[import-not-found]
25 Tool,
26 TextContent,
27 ContentBlock,
28 ImageContent,
29 PromptMessage,
30 CallToolResult,
31 EmbeddedResource,
32 ReadResourceResult,
33 BlobResourceContents,
34 TextResourceContents,
35 )
36 from mcp.client.session import ClientSession # type: ignore[import-not-found]
37 except ImportError as _err:
38 raise ImportError(
39 "The `mcp` package is required to use MCP helpers. Install it with: pip install anthropic[mcp]. Requires Python 3.10 or higher."
40 ) from _err
41
42 from ...types.beta import (
43 BetaBase64PDFSourceParam,
44 BetaPlainTextSourceParam,
45 BetaBase64ImageSourceParam,
46 BetaCacheControlEphemeralParam,
47 )
48 from ._beta_functions import (
49 ToolError,
50 BetaFunctionTool,
51 BetaAsyncFunctionTool,
52 BetaFunctionToolResultType,
53 beta_tool,
54 beta_async_tool,
55 )
56 from .._stainless_helpers import tag_helper
57 from ...types.beta.beta_tool_result_block_param import Content as BetaContent
58
59 __all__ = [
60 "mcp_tool",
61 "async_mcp_tool",
62 "mcp_content",
63 "mcp_message",
64 "mcp_resource_to_content",
65 "mcp_resource_to_file",
66 "UnsupportedMCPValueError",
67 ]
68
69 # mcp<2 exposes camelCase model fields (`tool.inputSchema`); mcp>=2 exposes
70 # snake_case (`tool.input_schema`). Read through this helper to support both.
71
72 _MCP_V1_NAMES = {
73 "input_schema": "inputSchema",
74 "mime_type": "mimeType",
75 "is_error": "isError",
76 "structured_content": "structuredContent",
77 }
78
79
80 def _mcp_field_v1_or_v2(obj: Any, name: str) -> Any:
81 try:
82 return getattr(obj, name)
83 except AttributeError:
84 return getattr(obj, _MCP_V1_NAMES[name])
85
86
87 _SUPPORTED_IMAGE_TYPES = frozenset({"image/jpeg", "image/png", "image/gif", "image/webp"})
88
89
90 class _TaggedDict(dict): # type: ignore[type-arg]
91 """A dict subclass that can carry a `_stainless_helper` attribute.
92
93 Behaves identically to a regular dict for serialization and isinstance checks,
94 but allows attaching tracking metadata that won't appear in JSON output.
95 """
96
97
98 class _TaggedTuple(tuple): # type: ignore[type-arg]
99 """A tuple subclass that can carry a `_stainless_helper` attribute."""
100
101
102 def _is_supported_image_type(mime_type: str) -> bool:
103 return mime_type in _SUPPORTED_IMAGE_TYPES
104
105
106 def _is_supported_resource_mime_type(mime_type: str | None) -> bool:
107 return (
108 mime_type is None
109 or mime_type.startswith("text/")
110 or mime_type == "application/pdf"
111 or _is_supported_image_type(mime_type)
112 )
113
114
115 class UnsupportedMCPValueError(Exception):
116 """Raised when an MCP value cannot be converted to a format supported by the Claude API."""
117
118
119 def mcp_content(
120 content: ContentBlock,
121 *,
122 cache_control: BetaCacheControlEphemeralParam | None = None,
123 ) -> BetaContent:
124 """Convert a single MCP content block to an Anthropic content block.
125
126 Handles text, image, and embedded resource content types.
127 Raises `UnsupportedMCPValueError` for audio and resource_link types.
128 """
129 if isinstance(content, TextContent):
130 block = _TaggedDict({"type": "text", "text": content.text})
131 if cache_control is not None:
132 block["cache_control"] = cache_control
133 tag_helper(block, "mcp_content")
134 return block # type: ignore[return-value]
135
136 if isinstance(content, ImageContent):
137 mime_type = _mcp_field_v1_or_v2(content, "mime_type")
138 if not _is_supported_image_type(mime_type):
139 raise UnsupportedMCPValueError(f"Unsupported image MIME type: {mime_type}")
140 image_block = _TaggedDict(
141 {
142 "type": "image",
143 "source": BetaBase64ImageSourceParam(
144 type="base64",
145 data=content.data,
146 media_type=mime_type, # type: ignore[typeddict-item]
147 ),
148 }
149 )
150 if cache_control is not None:
151 image_block["cache_control"] = cache_control
152 tag_helper(image_block, "mcp_content")
153 return image_block # type: ignore[return-value]
154
155 if isinstance(content, EmbeddedResource):
156 return _resource_contents_to_block(content.resource, cache_control=cache_control)
157
158 # audio, resource_link, or unknown
159 content_type = getattr(content, "type", type(content).__name__)
160 raise UnsupportedMCPValueError(f"Unsupported MCP content type: {content_type}")
161
162
163 def _resource_contents_to_block(
164 resource: TextResourceContents | BlobResourceContents,
165 *,
166 cache_control: BetaCacheControlEphemeralParam | None = None,
167 ) -> BetaContent:
168 """Convert MCP resource contents to an Anthropic content block."""
169 mime_type = _mcp_field_v1_or_v2(resource, "mime_type")
170
171 if mime_type is not None and _is_supported_image_type(mime_type):
172 if not isinstance(resource, BlobResourceContents):
173 raise UnsupportedMCPValueError(f"Image resource must have blob data, not text. URI: {resource.uri}")
174 image_block = _TaggedDict(
175 {
176 "type": "image",
177 "source": BetaBase64ImageSourceParam(
178 type="base64",
179 data=resource.blob,
180 media_type=mime_type, # type: ignore[typeddict-item]
181 ),
182 }
183 )
184 if cache_control is not None:
185 image_block["cache_control"] = cache_control
186 tag_helper(image_block, "mcp_resource_to_content")
187 return image_block # type: ignore[return-value]
188
189 if mime_type == "application/pdf":
190 if not isinstance(resource, BlobResourceContents):
191 raise UnsupportedMCPValueError(f"PDF resource must have blob data, not text. URI: {resource.uri}")
192 pdf_block = _TaggedDict(
193 {
194 "type": "document",
195 "source": BetaBase64PDFSourceParam(
196 type="base64",
197 data=resource.blob,
198 media_type="application/pdf",
199 ),
200 }
201 )
202 if cache_control is not None:
203 pdf_block["cache_control"] = cache_control
204 tag_helper(pdf_block, "mcp_resource_to_content")
205 return pdf_block # type: ignore[return-value]
206
207 if mime_type is None or mime_type.startswith("text/"):
208 if isinstance(resource, TextResourceContents):
209 data = resource.text
210 else:
211 data = base64.b64decode(resource.blob).decode("utf-8")
212 text_block = _TaggedDict(
213 {
214 "type": "document",
215 "source": BetaPlainTextSourceParam(
216 type="text",
217 data=data,
218 media_type="text/plain",
219 ),
220 }
221 )
222 if cache_control is not None:
223 text_block["cache_control"] = cache_control
224 tag_helper(text_block, "mcp_resource_to_content")
225 return text_block # type: ignore[return-value]
226
227 raise UnsupportedMCPValueError(f'Unsupported MIME type "{mime_type}" for resource: {resource.uri}')
228
229
230 def mcp_message(
231 message: PromptMessage,
232 *,
233 cache_control: BetaCacheControlEphemeralParam | None = None,
234 ) -> dict[str, Any]:
235 """Convert an MCP prompt message to an Anthropic `BetaMessageParam`."""
236 result = _TaggedDict(
237 {
238 "role": message.role,
239 "content": [mcp_content(message.content, cache_control=cache_control)],
240 }
241 )
242 tag_helper(result, "mcp_message")
243 return result
244
245
246 def mcp_resource_to_content(
247 result: ReadResourceResult,
248 *,
249 cache_control: BetaCacheControlEphemeralParam | None = None,
250 ) -> BetaContent:
251 """Convert MCP resource contents to an Anthropic content block.
252
253 Finds the first resource with a supported MIME type from the result's
254 `contents` list.
255 """
256 if not result.contents:
257 raise UnsupportedMCPValueError("Resource contents array must contain at least one item")
258
259 mime_types = [_mcp_field_v1_or_v2(c, "mime_type") for c in result.contents]
260 supported = next(
261 (
262 c
263 for c, mime_type in zip(result.contents, mime_types, strict=True)
264 if _is_supported_resource_mime_type(mime_type)
265 ),
266 None,
267 )
268 if supported is None:
269 mime_types = [m for m in mime_types if m is not None]
270 raise UnsupportedMCPValueError(
271 f"No supported MIME type found in resource contents. Available: {', '.join(mime_types)}"
272 )
273
274 return _resource_contents_to_block(supported, cache_control=cache_control)
275
276
277 def mcp_resource_to_file(
278 result: ReadResourceResult,
279 ) -> tuple[str | None, bytes, str | None]:
280 """Convert MCP resource contents to a file tuple for `files.upload()`.
281
282 Returns a `(filename, content_bytes, mime_type)` tuple compatible with
283 the SDK's `FileTypes`.
284 """
285 if not result.contents:
286 raise UnsupportedMCPValueError("Resource contents array must contain at least one item")
287
288 resource = result.contents[0]
289 uri_str = str(resource.uri)
290
291 path = urlparse(uri_str).path
292 name = path.rsplit("/", 1)[-1] if path else None
293
294 if isinstance(resource, BlobResourceContents):
295 content_bytes = base64.b64decode(resource.blob)
296 else:
297 content_bytes = resource.text.encode("utf-8")
298
299 file_tuple = _TaggedTuple((name, content_bytes, _mcp_field_v1_or_v2(resource, "mime_type")))
300 tag_helper(file_tuple, "mcp_resource_to_file")
301 return file_tuple
302
303
304 def _convert_tool_result(result: CallToolResult) -> BetaFunctionToolResultType:
305 """Convert MCP `CallToolResult` to a value suitable for returning from `call()`."""
306 if _mcp_field_v1_or_v2(result, "is_error"):
307 raise ToolError([mcp_content(item) for item in result.content])
308
309 structured_content = _mcp_field_v1_or_v2(result, "structured_content")
310 if not result.content and structured_content is not None:
311 return json.dumps(structured_content)
312
313 return [mcp_content(item) for item in result.content]
314
315
316 def mcp_tool(
317 tool: Tool,
318 client: ClientSession,
319 *,
320 cache_control: BetaCacheControlEphemeralParam | None = None,
321 defer_loading: bool | None = None,
322 allowed_callers: list[
323 Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"]
324 ]
325 | None = None,
326 eager_input_streaming: bool | None = None,
327 input_examples: Iterable[dict[str, object]] | None = None,
328 strict: bool | None = None,
329 ) -> BetaFunctionTool[Any]:
330 """Convert an MCP tool to a sync runnable tool for `tool_runner()`.
331
332 Example:
333
334 ```py
335 from anthropic.lib.tools.mcp import mcp_tool
336
337 tools_result = await mcp_client.list_tools()
338 runner = client.beta.messages.tool_runner(
339 model="claude-sonnet-4-20250514",
340 max_tokens=1024,
341 tools=[mcp_tool(t, mcp_client) for t in tools_result.tools],
342 messages=[{"role": "user", "content": "Use the available tools"}],
343 )
344 ```
345
346 Args:
347 tool: An MCP tool definition from `client.list_tools()`.
348 client: The MCP `ClientSession` used to call the tool.
349 cache_control: Cache control configuration.
350 defer_loading: If true, tool will not be included in initial system prompt.
351 allowed_callers: Which callers may use this tool.
352 eager_input_streaming: Enable eager input streaming for this tool.
353 input_examples: Example inputs for the tool.
354 strict: When true, guarantees schema validation on tool names and inputs.
355 """
356 import anyio.from_thread
357
358 tool_name = tool.name
359
360 def call_mcp(**kwargs: Any) -> BetaFunctionToolResultType:
361 result = anyio.from_thread.run(client.call_tool, tool_name, kwargs)
362 return _convert_tool_result(result)
363
364 result = beta_tool(
365 call_mcp,
366 name=tool_name,
367 description=tool.description,
368 input_schema=_mcp_field_v1_or_v2(tool, "input_schema"),
369 cache_control=cache_control,
370 defer_loading=defer_loading,
371 allowed_callers=allowed_callers,
372 eager_input_streaming=eager_input_streaming,
373 input_examples=input_examples,
374 strict=strict,
375 )
376 tag_helper(result, "mcp_tool")
377 return result
378
379
380 def async_mcp_tool(
381 tool: Tool,
382 client: ClientSession,
383 *,
384 cache_control: BetaCacheControlEphemeralParam | None = None,
385 defer_loading: bool | None = None,
386 allowed_callers: list[
387 Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"]
388 ]
389 | None = None,
390 eager_input_streaming: bool | None = None,
391 input_examples: Iterable[dict[str, object]] | None = None,
392 strict: bool | None = None,
393 ) -> BetaAsyncFunctionTool[Any]:
394 """Convert an MCP tool to an async runnable tool for `tool_runner()`.
395
396 Example:
397
398 ```py
399 from anthropic.lib.tools.mcp import async_mcp_tool
400
401 tools_result = await mcp_client.list_tools()
402 runner = await client.beta.messages.tool_runner(
403 model="claude-sonnet-4-20250514",
404 max_tokens=1024,
405 tools=[async_mcp_tool(t, mcp_client) for t in tools_result.tools],
406 messages=[{"role": "user", "content": "Use the available tools"}],
407 )
408 ```
409
410 Args:
411 tool: An MCP tool definition from `client.list_tools()`.
412 client: The MCP `ClientSession` used to call the tool.
413 cache_control: Cache control configuration.
414 defer_loading: If true, tool will not be included in initial system prompt.
415 allowed_callers: Which callers may use this tool.
416 eager_input_streaming: Enable eager input streaming for this tool.
417 input_examples: Example inputs for the tool.
418 strict: When true, guarantees schema validation on tool names and inputs.
419 """
420 tool_name = tool.name
421
422 async def call_mcp(**kwargs: Any) -> BetaFunctionToolResultType:
423 result = await client.call_tool(name=tool_name, arguments=kwargs)
424 return _convert_tool_result(result)
425
426 result = beta_async_tool(
427 call_mcp,
428 name=tool_name,
429 description=tool.description,
430 input_schema=_mcp_field_v1_or_v2(tool, "input_schema"),
431 cache_control=cache_control,
432 defer_loading=defer_loading,
433 allowed_callers=allowed_callers,
434 eager_input_streaming=eager_input_streaming,
435 input_examples=input_examples,
436 strict=strict,
437 )
438 tag_helper(result, "mcp_tool")
439 return result