SPB Git

Repository Public

mcp-connector.md 48.6 KB 1,505 lines markdown

1---2title: MCP connector3url: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector4description: Connect to remote MCP servers directly from the Messages API without an MCP client, and allowlist, denylist, or configure individual tools.5---67## Compatibility8- Status: Beta9- [Beta header](https://platform.claude.com/docs/en/api/beta-headers): `mcp-client-2025-11-20`10- [ZDR](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention): not eligible11- Platforms: Claude API (beta), Claude Platform on AWS (beta), Microsoft Foundry (beta); not available on Amazon Bedrock, Google Cloud1213Claude's Model Context Protocol (MCP) connector feature enables you to connect to remote MCP servers directly from the Messages API without a separate MCP client.1415<Note>16  The previous version of this feature (`mcp-client-2025-04-04`) is deprecated. See [Deprecated version: mcp-client-2025-04-04](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector#deprecated-version-mcp-client-2025-04-04).17</Note>1819## Key features2021* **Direct API integration:** Connect to MCP servers without implementing an MCP client22* **Tool calling support:** Access MCP tools through the Messages API23* **Flexible tool configuration:** Enable all tools, allowlist specific tools, or denylist unwanted tools24* **Per-tool configuration:** Configure individual tools with custom settings25* **OAuth authentication:** Support for OAuth Bearer tokens for authenticated servers26* **Multiple servers:** Connect to multiple MCP servers in a single request2728## When Claude uses MCP tools2930Once an MCP server is connected, Claude calls its tools when the user's request maps to a tool's described capability, either explicitly ("search Jira for open bugs") or implicitly ("what's blocking the release?" with a Jira server attached).3132Claude does **not** call an MCP tool for general knowledge questions about a connected service. Asking "how do Notion databases work?" with a Notion server attached is answered directly; asking "what's in my Projects database?" triggers the tool.3334You can steer how readily Claude calls MCP tools through your system prompt. See [When Claude uses tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview#when-claude-uses-tools) for general guidance and example phrasings.3536## Limitations3738* Of the feature set of the [MCP specification](https://modelcontextprotocol.io/introduction#explore-mcp), only [tool calls](https://modelcontextprotocol.io/docs/concepts/tools) are currently supported.39* The server must be publicly exposed through HTTP (supports both Streamable HTTP and SSE transports). Local STDIO servers cannot be connected directly.4041## Using the MCP connector in the Messages API4243The MCP connector uses two components:44451. **MCP server definition** (`mcp_servers` array): Defines server connection details (URL, authentication)462. **MCP toolset** (`tools` array): Configures which tools to enable and how to configure them4748### Basic example4950This example enables all tools from an MCP server with default configuration:5152<CodeGroup>53  ```bash cURL54  curl https://api.anthropic.com/v1/messages \55    -H "Content-Type: application/json" \56    -H "X-API-Key: $ANTHROPIC_API_KEY" \57    -H "anthropic-version: 2023-06-01" \58    -H "anthropic-beta: mcp-client-2025-11-20" \59    -d '{60      "model": "claude-opus-5",61      "max_tokens": 1000,62      "messages": [{"role": "user", "content": "What tools do you have available?"}],63      "mcp_servers": [64        {65          "type": "url",66          "url": "https://example-server.modelcontextprotocol.io/sse",67          "name": "example-mcp",68          "authorization_token": "YOUR_TOKEN"69        }70      ],71      "tools": [72        {73          "type": "mcp_toolset",74          "mcp_server_name": "example-mcp"75        }76      ]77    }'78  ```7980  ```bash CLI81  ant beta:messages create --beta mcp-client-2025-11-20 <<'YAML'82  model: claude-opus-583  max_tokens: 100084  messages:85    - role: user86      content: What tools do you have available?87  mcp_servers:88    - type: url89      url: https://example-server.modelcontextprotocol.io/sse90      name: example-mcp91      authorization_token: YOUR_TOKEN92  tools:93    - type: mcp_toolset94      mcp_server_name: example-mcp95  YAML96  ```9798  ```python Python99  client = anthropic.Anthropic()100101  response = client.beta.messages.create(102      model="claude-opus-5",103      max_tokens=1000,104      messages=[{"role": "user", "content": "What tools do you have available?"}],105      mcp_servers=[106          {107              "type": "url",108              "url": "https://example-server.modelcontextprotocol.io/sse",109              "name": "example-mcp",110              "authorization_token": "YOUR_TOKEN",111          }112      ],113      tools=[{"type": "mcp_toolset", "mcp_server_name": "example-mcp"}],114      betas=["mcp-client-2025-11-20"],115  )116117  print(response)118  ```119120  ```typescript TypeScript121  const anthropic = new Anthropic();122123  const response = await anthropic.beta.messages.create({124    model: "claude-opus-5",125    max_tokens: 1000,126    messages: [127      {128        role: "user",129        content: "What tools do you have available?"130      }131    ],132    mcp_servers: [133      {134        type: "url",135        url: "https://example-server.modelcontextprotocol.io/sse",136        name: "example-mcp",137        authorization_token: "YOUR_TOKEN"138      }139    ],140    tools: [141      {142        type: "mcp_toolset",143        mcp_server_name: "example-mcp"144      }145    ],146    betas: ["mcp-client-2025-11-20"]147  });148149  console.log(response);150  ```151152  ```csharp C#153  AnthropicClient client = new();154155  var parameters = new MessageCreateParams156  {157      Model = Model.ClaudeOpus5,158      MaxTokens = 1000,159      Messages = new List<BetaMessageParam>160      {161          new() { Role = Role.User, Content = "What tools do you have available?" }162      },163      McpServers = new List<BetaRequestMcpServerUrlDefinition>164      {165          new()166          {167              Url = "https://example-server.modelcontextprotocol.io/sse",168              Name = "example-mcp",169              AuthorizationToken = "YOUR_TOKEN"170          }171      },172      Tools = new List<BetaToolUnion>173      {174          new BetaMcpToolset("example-mcp")175      },176      Betas = [AnthropicBeta.McpClient2025_11_20]177  };178179  var message = await client.Beta.Messages.Create(parameters);180  Console.WriteLine(message);181  ```182183  ```go Go184  client := anthropic.NewClient()185186  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{187  	Model:     anthropic.ModelClaudeOpus5,188  	MaxTokens: 1000,189  	Messages: []anthropic.BetaMessageParam{190  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What tools do you have available?")),191  	},192  	MCPServers: []anthropic.BetaRequestMCPServerURLDefinitionParam{193  		{194  			URL:                "https://example-server.modelcontextprotocol.io/sse",195  			Name:               "example-mcp",196  			AuthorizationToken: anthropic.String("YOUR_TOKEN"),197  		},198  	},199  	Tools: []anthropic.BetaToolUnionParam{200  		{OfMCPToolset: &anthropic.BetaMCPToolsetParam{201  			MCPServerName: "example-mcp",202  		}},203  	},204  	Betas: []anthropic.AnthropicBeta{205  		anthropic.AnthropicBetaMCPClient2025_11_20,206  	},207  })208  if err != nil {209  	log.Fatal(err)210  }211  fmt.Println(response)212  ```213214  ```java Java215  import com.anthropic.models.beta.messages.BetaMcpToolset;216  // ...217  import com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition;218  // ...219220  void main() {221      AnthropicClient client = AnthropicOkHttpClient.fromEnv();222223      MessageCreateParams params = MessageCreateParams.builder()224          .model(Model.CLAUDE_OPUS_5)225          .maxTokens(1000L)226          .addUserMessage("What tools do you have available?")227          .addMcpServer(BetaRequestMcpServerUrlDefinition.builder()228              .url("https://example-server.modelcontextprotocol.io/sse")229              .name("example-mcp")230              .authorizationToken("YOUR_TOKEN")231              .build())232          .addTool(BetaMcpToolset.builder()233              .mcpServerName("example-mcp")234              .build())235          .addBeta(AnthropicBeta.MCP_CLIENT_2025_11_20)236          .build();237238      BetaMessage response = client.beta().messages().create(params);239      IO.println(response);240  }241  ```242243  ```php PHP244  $client = new Client();245246  $message = $client->beta->messages->create(247      maxTokens: 1000,248      messages: [249          ['role' => 'user', 'content' => 'What tools do you have available?']250      ],251      model: 'claude-opus-5',252      mcpServers: [253          [254              'type' => 'url',255              'url' => 'https://example-server.modelcontextprotocol.io/sse',256              'name' => 'example-mcp',257              'authorization_token' => 'YOUR_TOKEN',258          ],259      ],260      tools: [261          [262              'type' => 'mcp_toolset',263              'mcp_server_name' => 'example-mcp',264          ],265      ],266      betas: ['mcp-client-2025-11-20'],267  );268269  echo $message;270  ```271272  ```ruby Ruby273  client = Anthropic::Client.new274275  response = client.beta.messages.create(276    model: "claude-opus-5",277    max_tokens: 1000,278    messages: [279      { role: "user", content: "What tools do you have available?" }280    ],281    mcp_servers: [282      {283        type: "url",284        url: "https://example-server.modelcontextprotocol.io/sse",285        name: "example-mcp",286        authorization_token: "YOUR_TOKEN"287      }288    ],289    tools: [290      {291        type: "mcp_toolset",292        mcp_server_name: "example-mcp"293      }294    ],295    betas: ["mcp-client-2025-11-20"]296  )297298  puts response299  ```300</CodeGroup>301302## MCP server configuration303304Each MCP server in the `mcp_servers` array defines the connection details:305306```json307{308  "type": "url",309  "url": "https://example-server.modelcontextprotocol.io/sse",310  "name": "example-mcp",311  "authorization_token": "YOUR_TOKEN"312}313```314315### Field descriptions316317| Property              | Type   | Required | Description                                                                                                                                                                                                                                                                                                            |318| --------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |319| `type`                | string | Yes      | Currently only "url" is supported.                                                                                                                                                                                                                                                                                     |320| `url`                 | string | Yes      | The URL of the MCP server. Must start with https\://.                                                                                                                                                                                                                                                                  |321| `name`                | string | Yes      | A unique identifier for this MCP server. Must be referenced by exactly one MCPToolset in the `tools` array.                                                                                                                                                                                                            |322| `authorization_token` | string | No       | OAuth authorization token if required by the MCP server. See [Authentication](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector#authentication) for how to obtain one, or the [MCP specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) for protocol details. |323324## MCP toolset configuration325326The MCPToolset lives in the `tools` array and configures which tools from the MCP server are enabled and how they should be configured.327328### Basic structure329330```json331{332  "type": "mcp_toolset",333  "mcp_server_name": "example-mcp",334  "default_config": {335    "enabled": true,336    "defer_loading": false337  },338  "configs": {339    "specific_tool_name": {340      "enabled": true,341      "defer_loading": true342    }343  }344}345```346347### Field descriptions348349| Property          | Type   | Required | Description                                                                                                                             |350| ----------------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |351| `type`            | string | Yes      | Must be "mcp\_toolset".                                                                                                                 |352| `mcp_server_name` | string | Yes      | Must match a server name defined in the `mcp_servers` array.                                                                            |353| `default_config`  | object | No       | Default configuration applied to all tools in this set. Individual tool configs in `configs` override these defaults.                   |354| `configs`         | object | No       | Per-tool configuration overrides. Keys are tool names, values are configuration objects.                                                |355| `cache_control`   | object | No       | [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) cache breakpoint configuration for this toolset. |356357### Tool configuration options358359Each tool (whether configured in `default_config` or in `configs`) supports the following fields:360361| Property        | Type    | Default | Description                                                                                                                                                                 |362| --------------- | ------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |363| `enabled`       | boolean | `true`  | Whether this tool is enabled.                                                                                                                                               |364| `defer_loading` | boolean | `false` | If true, tool description is not sent to the model initially. Used with [Tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool). |365366For the full directory of Anthropic-provided tools and optional properties such as `defer_loading`, see the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference). To search across large tool sets, see [Tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool).367368### Configuration merging369370Configuration values merge with this precedence (highest to lowest):3713721. Tool-specific settings in `configs`3732. Set-level `default_config`3743. System defaults375376Example:377378```json379{380  "type": "mcp_toolset",381  "mcp_server_name": "google-calendar-mcp",382  "default_config": {383    "defer_loading": true384  },385  "configs": {386    "search_events": {387      "enabled": false388    }389  }390}391```392393Results in:394395* `search_events`: `enabled: false` (from configs), `defer_loading: true` (from default\_config)396* All other tools: `enabled: true` (system default), `defer_loading: true` (from default\_config)397398## Common configuration patterns399400### Enable all tools with default configuration401402The simplest pattern: enable all tools from a server:403404```json405{406  "type": "mcp_toolset",407  "mcp_server_name": "google-calendar-mcp"408}409```410411### Allowlist: enable only specific tools412413Set `enabled: false` as the default, then explicitly enable specific tools:414415```json416{417  "type": "mcp_toolset",418  "mcp_server_name": "google-calendar-mcp",419  "default_config": {420    "enabled": false421  },422  "configs": {423    "search_events": {424      "enabled": true425    },426    "create_event": {427      "enabled": true428    }429  }430}431```432433### Denylist: disable specific tools434435Enable all tools by default, then explicitly disable unwanted tools. Denylisting write or destructive tools is recommended when building read-only assistants, or when you want a human confirmation step before state changes:436437```json438{439  "type": "mcp_toolset",440  "mcp_server_name": "google-calendar-mcp",441  "configs": {442    "delete_all_events": {443      "enabled": false444    },445    "share_calendar_publicly": {446      "enabled": false447    }448  }449}450```451452### Mixed: allowlist with per-tool configuration453454Combine allowlisting with custom configuration for each tool:455456```json457{458  "type": "mcp_toolset",459  "mcp_server_name": "google-calendar-mcp",460  "default_config": {461    "enabled": false,462    "defer_loading": true463  },464  "configs": {465    "search_events": {466      "enabled": true,467      "defer_loading": false468    },469    "list_events": {470      "enabled": true471    }472  }473}474```475476In this example:477478* `search_events` is enabled with `defer_loading: false`479* `list_events` is enabled with `defer_loading: true` (inherited from default\_config)480* All other tools are disabled481482## Validation rules483484The API enforces these validation rules:485486* **Server must exist:** The `mcp_server_name` in an MCPToolset must match a server defined in the `mcp_servers` array487* **Server must be used:** Every MCP server defined in `mcp_servers` must be referenced by exactly one MCPToolset488* **Unique toolset per server:** Each MCP server can only be referenced by one MCPToolset489* **Unknown tool names:** If a tool name in `configs` doesn't exist on the MCP server, a backend warning is logged but no error is returned (MCP servers may have dynamic tool availability)490491## Response content types492493When Claude uses MCP tools, the response includes two new content block types:494495### MCP tool use block496497```json498{499  "type": "mcp_tool_use",500  "id": "mcptoolu_014Q35RayjACSWkSj4X2yov1",501  "name": "echo",502  "server_name": "example-mcp",503  "input": { "param1": "value1", "param2": "value2" }504}505```506507### MCP tool result block508509```json510{511  "type": "mcp_tool_result",512  "tool_use_id": "mcptoolu_014Q35RayjACSWkSj4X2yov1",513  "is_error": false,514  "content": [515    {516      "type": "text",517      "text": "Hello"518    }519  ]520}521```522523## Multiple MCP servers524525You can connect to multiple MCP servers by including multiple server definitions in `mcp_servers` and a corresponding MCPToolset for each in the `tools` array:526527```json528{529  "model": "claude-opus-5",530  "max_tokens": 1000,531  "messages": [532    {533      "role": "user",534      "content": "Use tools from both mcp-server-1 and mcp-server-2 to complete this task"535    }536  ],537  "mcp_servers": [538    {539      "type": "url",540      "url": "https://mcp.example1.com/sse",541      "name": "mcp-server-1",542      "authorization_token": "TOKEN1"543    },544    {545      "type": "url",546      "url": "https://mcp.example2.com/sse",547      "name": "mcp-server-2",548      "authorization_token": "TOKEN2"549    }550  ],551  "tools": [552    {553      "type": "mcp_toolset",554      "mcp_server_name": "mcp-server-1"555    },556    {557      "type": "mcp_toolset",558      "mcp_server_name": "mcp-server-2",559      "default_config": {560        "defer_loading": true561      }562    }563  ]564}565```566567With many tools available, Claude selects based on tool names and descriptions. Clear, specific tool descriptions improve selection accuracy. For large tool sets (dozens of tools across several servers), consider enabling [`defer_loading`](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector#tool-configuration-options) with the [Tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) so only relevant tools are surfaced per query.568569## Authentication570571For MCP servers that require OAuth authentication, you'll need to obtain an access token. The MCP connector beta supports passing an `authorization_token` parameter in the MCP server definition. API consumers are expected to handle the OAuth flow and obtain the access token prior to making the API call, and to refresh the token as needed.572573### Obtaining an access token for testing574575The MCP inspector can guide you through the process of obtaining an access token for testing purposes.5765771. Run the inspector with the following command. You need Node.js installed on your machine.578579   ```bash580   npx @modelcontextprotocol/inspector581   ```5825832. In the sidebar on the left, for **Transport type**, select either **SSE** or **Streamable HTTP**.5845853. Enter the URL of the MCP server.5865874. In the right area, click **Open Auth Settings** after **Need to configure authentication?**.5885895. Click **Quick OAuth Flow** and authorize on the OAuth screen.5905916. Follow the steps in the **OAuth Flow Progress** section of the inspector and click **Continue** until you reach **Authentication complete**.5925937. Copy the `access_token` value.5945958. Paste it into the `authorization_token` field in your MCP server configuration.596597### Using the access token598599Once you've obtained an access token using either of the preceding OAuth flows, you can use it in your MCP server configuration:600601```json602{603  "mcp_servers": [604    {605      "type": "url",606      "url": "https://example-server.modelcontextprotocol.io/sse",607      "name": "authenticated-server",608      "authorization_token": "YOUR_ACCESS_TOKEN_HERE"609    }610  ]611}612```613614For detailed explanations of the OAuth flow, refer to the [Authorization section](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) in the MCP specification.615616## Client-side MCP helpers617618If you manage your own MCP client connection (for example, with local stdio servers, MCP prompts, or MCP resources), the SDKs provide helper functions that convert between MCP types and Claude API types. This eliminates manual conversion code when using an MCP SDK for your language (for example, the [TypeScript MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk)) alongside the Anthropic SDK.619620<Note>621  Use the [`mcp_servers` API parameter](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector#using-the-mcp-connector-in-the-messages-api) when you have remote servers accessible by URL and only need tool support. Use the client-side helpers when you need local servers, prompts, resources, or more control over the connection with the base SDK.622</Note>623624### Installation625626Install both the Anthropic SDK and the MCP SDK:627628<Tabs>629  <Tab title="Python">630    The MCP helpers are included in the `mcp` extra, which requires Python 3.10 or later:631632    ```bash633    pip install "anthropic[mcp]"634    ```635  </Tab>636637  <Tab title="TypeScript">638    ```bash639    npm install @anthropic-ai/sdk @modelcontextprotocol/sdk640    ```641  </Tab>642643  <Tab title="C#">644    The helpers live in the separate `Anthropic.Mcp` package; the MCP client itself comes from the official [ModelContextProtocol package](https://www.nuget.org/packages/ModelContextProtocol):645646    ```bash647    dotnet add package Anthropic.Mcp648    dotnet add package ModelContextProtocol649    ```650  </Tab>651652  <Tab title="Go">653    The helpers live in the `mcp` subpackage of the Go SDK, which builds on the [MCP Go SDK](https://github.com/modelcontextprotocol/go-sdk):654655    ```bash656    go get github.com/anthropics/anthropic-sdk-go/mcp657    ```658  </Tab>659660  <Tab title="Java">661    The helpers live in the separate `anthropic-java-mcp` artifact, which requires Java 17 or later (the base SDK supports Java 8). Add it alongside the base `anthropic-java` dependency:662663    <Tabs>664      <Tab title="Gradle">665        ```kotlin666        implementation("com.anthropic:anthropic-java:2.63.0")667        implementation("com.anthropic:anthropic-java-mcp:2.63.0")668        ```669      </Tab>670671      <Tab title="Maven">672        ```xml673        <dependency>674            <groupId>com.anthropic</groupId>675            <artifactId>anthropic-java</artifactId>676            <version>2.63.0</version>677        </dependency>678        <dependency>679            <groupId>com.anthropic</groupId>680            <artifactId>anthropic-java-mcp</artifactId>681            <version>2.63.0</version>682        </dependency>683        ```684      </Tab>685    </Tabs>686  </Tab>687688  <Tab title="PHP">689    The helpers use the official [MCP PHP SDK](https://packagist.org/packages/mcp/sdk):690691    ```bash692    composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7" "mcp/sdk"693    ```694  </Tab>695696  <Tab title="Ruby">697    The helpers use the official [`mcp` gem](https://rubygems.org/gems/mcp):698699    ```bash700    bundle add anthropic mcp701    ```702  </Tab>703</Tabs>704705### Available helpers706707Import the helpers for your language:708709<CodeGroup exclude="shell">710  ```python Python711  from anthropic.lib.tools.mcp import (712      async_mcp_tool,713      mcp_message,714      mcp_resource_to_content,715      mcp_resource_to_file,716  )717  ```718719  ```typescript TypeScript720  import {721    mcpTools,722    mcpMessages,723    mcpResourceToContent,724    mcpResourceToFile725  } from "@anthropic-ai/sdk/helpers/beta/mcp";726  ```727728  ```csharp C#729  using Anthropic.Helpers.Beta;730  using Anthropic.Helpers.Beta.Mcp;731  ```732733  ```go Go734  import (735  	"github.com/anthropics/anthropic-sdk-go/mcp"736  )737738  ```739740  ```java Java741  import com.anthropic.helpers.McpBetaTool;742  import com.anthropic.mcp.BetaMcp;743  ```744745  ```php PHP746  use Anthropic\Lib\Tools\BetaMcp;747  ```748749  ```ruby Ruby750  require "anthropic"751752  # The helpers are exposed on the Anthropic::Mcp module753  ```754</CodeGroup>755756Helper names and exact signatures follow each language's conventions; this table shows the TypeScript forms:757758| Helper                           | Description                                                                             |759| -------------------------------- | --------------------------------------------------------------------------------------- |760| `mcpTools(tools, mcpClient)`     | Converts MCP tools to Claude API tools for use with `client.beta.messages.toolRunner()` |761| `mcpMessages(messages)`          | Converts MCP prompt messages to Claude API message format                               |762| `mcpResourceToContent(resource)` | Converts an MCP resource to a Claude API content block                                  |763| `mcpResourceToFile(resource)`    | Converts an MCP resource to a file object for upload                                    |764765### Use MCP tools766767Convert MCP tools for use with the SDK's [tool runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner), which handles tool execution automatically:768769<CodeGroup exclude="shell">770  ```python Python771  from anthropic.lib.tools.mcp import async_mcp_tool772  from mcp import ClientSession773  from mcp.client.stdio import StdioServerParameters, stdio_client774775  client = AsyncAnthropic()776777778  async def main() -> None:779      # Connect to an MCP server780      server_params = StdioServerParameters(command="mcp-server")781      async with stdio_client(server_params) as (read, write):782          async with ClientSession(read, write) as mcp_client:783              await mcp_client.initialize()784785              # List tools and convert them for the Claude API786              tools_result = await mcp_client.list_tools()787              runner = client.beta.messages.tool_runner(788                  model="claude-opus-5",789                  max_tokens=1024,790                  messages=[791                      {"role": "user", "content": "What tools do you have available?"},792                  ],793                  tools=[async_mcp_tool(tool, mcp_client) for tool in tools_result.tools],794              )795796              final_message = await runner.until_done()797              print(final_message)798799800  asyncio.run(main())801  ```802803  ```typescript TypeScript804  import {805    mcpTools,806    type MCPCallToolResultLike,807    type MCPClientLike808  } from "@anthropic-ai/sdk/helpers/beta/mcp";809  import { Client } from "@modelcontextprotocol/sdk/client/index.js";810  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";811812  const anthropic = new Anthropic();813814  // Connect to an MCP server815  const transport = new StdioClientTransport({ command: "mcp-server", args: [] });816  const mcpClient = new Client({ name: "my-client", version: "1.0.0" });817  await mcpClient.connect(transport);818819  // List tools and convert them for the Claude API820  const { tools } = await mcpClient.listTools();821822  // The MCP SDK's callTool return type still includes a legacy result shape that823  // mcpTools does not accept; narrow it. Drop this once MCPClientLike widens.824  const mcpClientForTools: MCPClientLike = {825    callTool: (params) => mcpClient.callTool(params) as Promise<MCPCallToolResultLike>826  };827828  const finalMessage = await anthropic.beta.messages.toolRunner({829    model: "claude-opus-5",830    max_tokens: 1024,831    messages: [{ role: "user", content: "What tools do you have available?" }],832    tools: mcpTools(tools, mcpClientForTools)833  });834835  console.log(finalMessage);836  ```837838  ```csharp C#839  using Anthropic.Helpers.Beta;840  using Anthropic.Helpers.Beta.Mcp;841  using Anthropic.Models.Beta.Messages;842  using ModelContextProtocol.Client;843  using Messages = Anthropic.Models.Messages;844845  var anthropic = new AnthropicClient();846847  // Connect to an MCP server848  await using var mcpClient = await McpClient.CreateAsync(849      new StdioClientTransport(new StdioClientTransportOptions { Command = "mcp-server" })850  );851852  // List tools and convert them for the Claude API853  var tools = await BetaMcp.ListToolsAsync(mcpClient);854  var runner = anthropic.Beta.Messages.ToolRunner(855      new MessageCreateParams856      {857          Model = Messages::Model.ClaudeOpus5,858          MaxTokens = 1024,859          Messages =860          [861              new BetaMessageParam862              {863                  Role = Role.User,864                  Content = "What tools do you have available?",865              },866          ],867      },868      tools869  );870871  var finalMessage = await runner.RunUntilDoneAsync();872  Console.WriteLine(finalMessage);873  ```874875  ```go Go876  import (877  // ...878879  // ...880  	"github.com/anthropics/anthropic-sdk-go/mcp"881  	mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"882  )883884  func main() {885  	client := anthropic.NewClient()886  	ctx := context.Background()887888  	// Connect to an MCP server889  	mcpClient := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "my-client", Version: "1.0.0"}, nil)890  	session, err := mcpClient.Connect(ctx, &mcpsdk.CommandTransport{Command: exec.Command("mcp-server")}, nil)891  	if err != nil {892  		log.Fatal(err)893  	}894  	defer session.Close()895896  	// List tools and convert them for the Claude API897  	toolsResult, err := session.ListTools(ctx, nil)898  	if err != nil {899  		log.Fatal(err)900  	}901  	betaTools, err := mcp.NewBetaTools(toolsResult.Tools, session)902  	if err != nil {903  		log.Fatal(err)904  	}905906  	runner := client.Beta.Messages.NewToolRunner(betaTools, anthropic.BetaToolRunnerParams{907  		BetaMessageNewParams: anthropic.BetaMessageNewParams{908  			Model:     anthropic.ModelClaudeOpus5,909  			MaxTokens: 1024,910  			Messages: []anthropic.BetaMessageParam{911  				anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What tools do you have available?")),912  			},913  		},914  	})915916  	finalMessage, err := runner.RunToCompletion(ctx)917  	if err != nil {918  		log.Fatal(err)919  	}920  	fmt.Println(finalMessage.RawJSON())921  }922923  ```924925  ```java Java926  import com.anthropic.helpers.BetaToolRunner;927  import com.anthropic.helpers.McpBetaTool;928  import com.anthropic.mcp.BetaMcp;929  import com.anthropic.models.beta.messages.BetaMessage;930  import com.anthropic.models.beta.messages.MessageCreateParams;931  import com.anthropic.models.messages.Model;932  import io.modelcontextprotocol.client.McpClient;933  import io.modelcontextprotocol.client.McpSyncClient;934  import io.modelcontextprotocol.client.transport.ServerParameters;935  import io.modelcontextprotocol.client.transport.StdioClientTransport;936  import io.modelcontextprotocol.json.McpJsonDefaults;937  import io.modelcontextprotocol.spec.McpSchema;938  // ...939940  void main() throws Exception {941      AnthropicClient anthropic = AnthropicOkHttpClient.fromEnv();942943      // Connect to an MCP server944      StdioClientTransport transport = new StdioClientTransport(945              ServerParameters.builder("mcp-server").build(), McpJsonDefaults.getMapper());946947      try (McpSyncClient mcpClient = McpClient.sync(transport)948              .clientInfo(new McpSchema.Implementation("my-client", "1.0.0"))949              .build()) {950951          mcpClient.initialize();952953          // List tools and convert them for the Claude API954          List<McpBetaTool> betaTools = BetaMcp.mcpTools(mcpClient.listTools().tools(), mcpClient);955956          MessageCreateParams params = MessageCreateParams.builder()957                  .model(Model.CLAUDE_OPUS_5)958                  .maxTokens(1024L)959                  .addUserMessage("What tools do you have available?")960                  .addTools(betaTools)961                  .build();962963          // The runner yields one message per assistant turn; the last is the final response964          BetaToolRunner runner = anthropic.beta().messages().toolRunner(params);965          BetaMessage finalMessage = null;966          for (BetaMessage message : runner) {967              finalMessage = message;968          }969          IO.println(finalMessage);970      }971  }972  ```973974  ```php PHP975  use Anthropic\Lib\Tools\BetaMcp;976  use Mcp\Client;977  use Mcp\Client\Transport\HttpTransport;978979  $anthropic = new Anthropic();980981  // Connect to an MCP server. The PHP MCP client connects over HTTP; point this982  // at your server's endpoint.983  $mcp = Client::builder()->build();984  $mcp->connect(new HttpTransport('http://localhost:8000/mcp'));985986  // List tools and convert them for the Claude API987  $runner = $anthropic->beta->messages->toolRunner(988      maxTokens: 1024,989      messages: [['role' => 'user', 'content' => 'What tools do you have available?']],990      model: 'claude-opus-5',991      tools: BetaMcp::tools($mcp->listTools()->tools, $mcp),992  );993994  echo $runner->runUntilDone(), "\n";995  ```996997  ```ruby Ruby998  require "mcp"9991000  anthropic = Anthropic::Client.new10011002  # Connect to an MCP server1003  transport = MCP::Client::Stdio.new(command: "mcp-server")1004  mcp_client = MCP::Client.new(transport: transport)1005  mcp_client.connect10061007  # List tools and convert them for the Claude API1008  runner = anthropic.beta.messages.tool_runner(1009    model: "claude-opus-5",1010    max_tokens: 1024,1011    messages: [{ role: "user", content: "What tools do you have available?" }],1012    tools: Anthropic::Mcp.tools(mcp_client.tools, mcp_client)1013  )10141015  final_message = runner.run_until_finished.last1016  puts final_message1017  ```1018</CodeGroup>10191020### Use MCP prompts10211022Convert MCP prompt messages into Claude API message format:10231024<CodeGroup exclude="shell">1025  ```python Python1026  from anthropic.lib.tools.mcp import mcp_message10271028  prompt = await mcp_client.get_prompt(name="my-prompt")1029  response = await client.beta.messages.create(1030      model="claude-opus-5",1031      max_tokens=1024,1032      messages=[mcp_message(message) for message in prompt.messages],1033  )10341035  print(response)1036  ```10371038  ```typescript TypeScript1039  import { mcpMessages } from "@anthropic-ai/sdk/helpers/beta/mcp";10401041  const { messages } = await mcpClient.getPrompt({ name: "my-prompt" });1042  const response = await anthropic.beta.messages.create({1043    model: "claude-opus-5",1044    max_tokens: 1024,1045    messages: mcpMessages(messages)1046  });10471048  console.log(response);1049  ```10501051  ```csharp C#1052  var prompt = await mcpClient.GetPromptAsync("my-prompt");1053  var response = await anthropic.Beta.Messages.Create(1054      new MessageCreateParams1055      {1056          Model = Messages::Model.ClaudeOpus5,1057          MaxTokens = 1024,1058          Messages = BetaMcp.Messages(prompt.Messages),1059      }1060  );10611062  Console.WriteLine(response);1063  ```10641065  ```go Go1066  prompt, err := session.GetPrompt(ctx, &mcpsdk.GetPromptParams{Name: "my-prompt"})1067  if err != nil {1068  	log.Fatal(err)1069  }10701071  messages := make([]anthropic.BetaMessageParam, 0, len(prompt.Messages))1072  for _, promptMessage := range prompt.Messages {1073  	message, err := mcp.ToMessage(promptMessage)1074  	if err != nil {1075  		log.Fatal(err)1076  	}1077  	messages = append(messages, message)1078  }10791080  response, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{1081  	Model:     anthropic.ModelClaudeOpus5,1082  	MaxTokens: 1024,1083  	Messages:  messages,1084  })1085  if err != nil {1086  	log.Fatal(err)1087  }1088  fmt.Println(response.RawJSON())1089  ```10901091  ```java Java1092  McpSchema.GetPromptResult prompt = mcpClient.getPrompt(1093          new McpSchema.GetPromptRequest("my-prompt", Map.of()));10941095  BetaMessage response = anthropic.beta().messages().create(MessageCreateParams.builder()1096          .model(Model.CLAUDE_OPUS_5)1097          .maxTokens(1024L)1098          .messages(BetaMcp.mcpMessages(prompt.messages()))1099          .build());11001101  IO.println(response);1102  ```11031104  ```php PHP1105  $prompt = $mcp->getPrompt('my-prompt');11061107  $response = $anthropic->beta->messages->create(1108      maxTokens: 1024,1109      messages: array_map(BetaMcp::message(...), $prompt->messages),1110      model: 'claude-opus-5',1111  );11121113  echo $response, "\n";1114  ```11151116  ```ruby Ruby1117  prompt = mcp_client.get_prompt(name: "my-prompt")11181119  response = anthropic.beta.messages.create(1120    model: "claude-opus-5",1121    max_tokens: 1024,1122    messages: prompt["messages"].map { |message| Anthropic::Mcp.message(message) }1123  )11241125  puts response1126  ```1127</CodeGroup>11281129### Use MCP resources11301131Convert MCP resources into content blocks to include in messages, or into file objects for upload:11321133<CodeGroup exclude="shell">1134  ```python Python1135  from anthropic.lib.tools.mcp import (1136      mcp_resource_to_content,1137      mcp_resource_to_file,1138  )11391140  # As a content block in a message1141  resource = await mcp_client.read_resource(uri="file:///path/to/doc.txt")1142  response = await client.beta.messages.create(1143      model="claude-opus-5",1144      max_tokens=1024,1145      messages=[1146          {1147              "role": "user",1148              "content": [1149                  mcp_resource_to_content(resource),1150                  {"type": "text", "text": "Summarize this document"},1151              ],1152          }1153      ],1154  )1155  print(response)11561157  # As a file upload1158  file_resource = await mcp_client.read_resource(1159      uri="file:///path/to/data.json",1160  )1161  uploaded = await client.files.upload(1162      file=mcp_resource_to_file(file_resource),1163  )1164  print(uploaded.id)1165  ```11661167  ```typescript TypeScript1168  import { mcpResourceToContent, mcpResourceToFile } from "@anthropic-ai/sdk/helpers/beta/mcp";11691170  // As a content block in a message1171  const resource = await mcpClient.readResource({ uri: "file:///path/to/doc.txt" });1172  const response = await anthropic.beta.messages.create({1173    model: "claude-opus-5",1174    max_tokens: 1024,1175    messages: [1176      {1177        role: "user",1178        content: [1179          mcpResourceToContent(resource),1180          { type: "text", text: "Summarize this document" }1181        ]1182      }1183    ]1184  });1185  console.log(response);11861187  // As a file upload1188  const fileResource = await mcpClient.readResource({ uri: "file:///path/to/data.json" });1189  const uploaded = await anthropic.files.upload({ file: mcpResourceToFile(fileResource) });1190  console.log(uploaded.id);1191  ```11921193  ```csharp C#1194  // As a content block in a message1195  var resource = await mcpClient.ReadResourceAsync("file:///path/to/doc.txt");1196  var response = await anthropic.Beta.Messages.Create(1197      new MessageCreateParams1198      {1199          Model = Messages::Model.ClaudeOpus5,1200          MaxTokens = 1024,1201          Messages =1202          [1203              new BetaMessageParam1204              {1205                  Role = Role.User,1206                  Content = new BetaMessageParamContent(1207                      [1208                          BetaMcp.ResourceToContent(resource),1209                          new BetaTextBlockParam { Text = "Summarize this document" },1210                      ]1211                  ),1212              },1213          ],1214      }1215  );12161217  Console.WriteLine(response);12181219  // As a file upload1220  var fileResource = await mcpClient.ReadResourceAsync("file:///path/to/data.json");1221  var (filename, data, mediaType) = BetaMcp.ResourceToFile(fileResource);12221223  // Build the file part explicitly so the resource's filename and MIME type1224  // carry through to the upload.1225  var file = new BinaryContent { Stream = new MemoryStream(data), FileName = filename };1226  if (mediaType is not null)1227  {1228      file.ContentType = new(mediaType);1229  }12301231  var uploaded = await anthropic.Files.Upload(new FileUploadParams { File = file });1232  Console.WriteLine(uploaded.ID);1233  ```12341235  ```go Go1236  // As a content block in a message1237  resource, err := session.ReadResource(ctx, &mcpsdk.ReadResourceParams{URI: "file:///path/to/doc.txt"})1238  if err != nil {1239  	log.Fatal(err)1240  }1241  block, err := mcp.ResourceToBlock(resource)1242  if err != nil {1243  	log.Fatal(err)1244  }12451246  response, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{1247  	Model:     anthropic.ModelClaudeOpus5,1248  	MaxTokens: 1024,1249  	Messages: []anthropic.BetaMessageParam{1250  		anthropic.NewBetaUserMessage(1251  			// ResourceToBlock returns the tool-result content union; message1252  			// content is a separate union type, so re-wrap the shared variants1253  			// (mcp.ToMessage does the same internally).1254  			anthropic.BetaContentBlockParamUnion{1255  				OfText:     block.OfText,1256  				OfImage:    block.OfImage,1257  				OfDocument: block.OfDocument,1258  			},1259  			anthropic.NewBetaTextBlock("Summarize this document"),1260  		),1261  	},1262  })1263  if err != nil {1264  	log.Fatal(err)1265  }1266  fmt.Println(response.RawJSON())12671268  // As a file upload1269  fileResult, err := session.ReadResource(ctx, &mcpsdk.ReadResourceParams{URI: "file:///path/to/data.json"})1270  if err != nil {1271  	log.Fatal(err)1272  }1273  fileReader, err := mcp.ResourceToFile(fileResult)1274  if err != nil {1275  	log.Fatal(err)1276  }1277  uploaded, err := client.Files.Upload(ctx, anthropic.FileUploadParams{File: fileReader})1278  if err != nil {1279  	log.Fatal(err)1280  }1281  fmt.Println(uploaded.ID)1282  ```12831284  ```java Java1285  // As a content block in a message1286  McpSchema.ReadResourceResult resource = mcpClient.readResource(1287          new McpSchema.ReadResourceRequest("file:///path/to/doc.txt"));12881289  List<BetaContentBlockParam> content =1290          new ArrayList<>(BetaMcp.mcpResourceContents(resource));1291  content.add(BetaContentBlockParam.ofText(1292          BetaTextBlockParam.builder().text("Summarize this document").build()));12931294  BetaMessage response = anthropic.beta().messages().create(MessageCreateParams.builder()1295          .model(Model.CLAUDE_OPUS_5)1296          .maxTokens(1024L)1297          .addUserMessageOfBetaContentBlockParams(content)1298          .build());12991300  IO.println(response);13011302  // As a file upload1303  McpSchema.ReadResourceResult fileResource = mcpClient.readResource(1304          new McpSchema.ReadResourceRequest("file:///path/to/data.json"));13051306  McpResourceFile resourceFile = BetaMcp.mcpResourceFiles(fileResource).getFirst();13071308  // Build the file part explicitly so the resource's filename and MIME type1309  // carry through to the upload.1310  MultipartField.Builder<InputStream> fileField = MultipartField.<InputStream>builder()1311          .value(new ByteArrayInputStream(resourceFile.content()))1312          .filename(resourceFile.filename());1313  if (resourceFile.mimeType() != null) {1314      fileField.contentType(resourceFile.mimeType());1315  }13161317  var uploaded = anthropic.files().upload(FileUploadParams.builder()1318          .file(fileField.build())1319          .build());13201321  IO.println(uploaded.id());1322  ```13231324  ```php PHP1325  // As a content block in a message1326  $resource = $mcp->readResource('file:///path/to/doc.txt');13271328  $response = $anthropic->beta->messages->create(1329      maxTokens: 1024,1330      messages: [1331          [1332              'role' => 'user',1333              'content' => [1334                  BetaMcp::resourceToContent($resource),1335                  ['type' => 'text', 'text' => 'Summarize this document'],1336              ],1337          ],1338      ],1339      model: 'claude-opus-5',1340  );13411342  echo $response, "\n";13431344  // As a file upload1345  $fileResource = $mcp->readResource('file:///path/to/data.json');1346  $file = $anthropic->files->upload(file: BetaMcp::resourceToFile($fileResource));1347  echo $file->id, "\n";1348  ```13491350  ```ruby Ruby1351  # As a content block in a message1352  resource = mcp_client.read_resource(uri: "file:///path/to/doc.txt")13531354  response = anthropic.beta.messages.create(1355    model: "claude-opus-5",1356    max_tokens: 1024,1357    messages: [1358      {1359        role: "user",1360        content: [1361          *Anthropic::Mcp.resource_to_contents(resource),1362          { type: "text", text: "Summarize this document" }1363        ]1364      }1365    ]1366  )13671368  puts response13691370  # As a file upload1371  file_resource = mcp_client.read_resource(uri: "file:///path/to/data.json")1372  file = Anthropic::Mcp.resource_to_files(file_resource).first1373  uploaded_file = anthropic.files.upload(file: file)1374  puts uploaded_file.id1375  ```1376</CodeGroup>13771378### Error handling13791380The conversion functions throw `UnsupportedMCPValueError` if an MCP value isn't supported by the Claude API (in Go, the helpers return an `UnsupportedValueError`; in Java and C#, they throw `AnthropicInvalidDataException`). This can happen with unsupported content types, MIME types, or resource links (resolve resource links with your MCP client before converting).13811382## Batch requests13831384You can include `mcp_servers` in [Message Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing) requests. MCP tool calls through the Batches API are priced the same as those in regular Messages API requests.13851386## Data retention13871388The MCP connector is not covered by ZDR arrangements. Data exchanged with MCP servers, including tool definitions and execution results, is retained according to Anthropic's standard data retention policy.13891390For ZDR eligibility across all features, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).13911392## Migration guide13931394If you're using the deprecated `mcp-client-2025-04-04` beta header, follow this guide to migrate to the new version.13951396### Key changes139713981. **New beta header:** Change from `mcp-client-2025-04-04` to `mcp-client-2025-11-20`13992. **Tool configuration moved:** Tool configuration now lives in the `tools` array as MCPToolset objects, not in the MCP server definition14003. **More flexible configuration:** New pattern supports allowlisting, denylisting, and per-tool configuration14011402### Migration steps14031404**Before (deprecated):**14051406```json1407{1408  "model": "claude-opus-5",1409  "max_tokens": 1000,1410  "messages": [1411    // ...1412  ],1413  "mcp_servers": [1414    {1415      "type": "url",1416      "url": "https://mcp.example.com/sse",1417      "name": "example-mcp",1418      "authorization_token": "YOUR_TOKEN",1419      "tool_configuration": {1420        "enabled": true,1421        "allowed_tools": ["tool1", "tool2"]1422      }1423    }1424  ]1425}1426```14271428**After (current):**14291430```json1431{1432  "model": "claude-opus-5",1433  "max_tokens": 1000,1434  "messages": [1435    // ...1436  ],1437  "mcp_servers": [1438    {1439      "type": "url",1440      "url": "https://mcp.example.com/sse",1441      "name": "example-mcp",1442      "authorization_token": "YOUR_TOKEN"1443    }1444  ],1445  "tools": [1446    {1447      "type": "mcp_toolset",1448      "mcp_server_name": "example-mcp",1449      "default_config": {1450        "enabled": false1451      },1452      "configs": {1453        "tool1": {1454          "enabled": true1455        },1456        "tool2": {1457          "enabled": true1458        }1459      }1460    }1461  ]1462}1463```14641465### Common migration patterns14661467| Old pattern                                 | New pattern                                                                             |1468| ------------------------------------------- | --------------------------------------------------------------------------------------- |1469| No `tool_configuration` (all tools enabled) | MCPToolset with no `default_config` or `configs`                                        |1470| `tool_configuration.enabled: false`         | MCPToolset with `default_config.enabled: false`                                         |1471| `tool_configuration.allowed_tools: [...]`   | MCPToolset with `default_config.enabled: false` and specific tools enabled in `configs` |14721473## Deprecated version: mcp-client-2025-04-0414741475<Note type="warning">1476  This version is deprecated. Migrate to `mcp-client-2025-11-20` using the preceding [migration guide](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector#migration-guide).1477</Note>14781479The previous version of the MCP connector included tool configuration directly in the MCP server definition:14801481```json1482{1483  "mcp_servers": [1484    {1485      "type": "url",1486      "url": "https://example-server.modelcontextprotocol.io/sse",1487      "name": "example-mcp",1488      "authorization_token": "YOUR_TOKEN",1489      "tool_configuration": {1490        "enabled": true,1491        "allowed_tools": ["example_tool_1", "example_tool_2"]1492      }1493    }1494  ]1495}1496```14971498### Deprecated field descriptions14991500| Property                           | Type    | Description                                                        |1501| ---------------------------------- | ------- | ------------------------------------------------------------------ |1502| `tool_configuration`               | object  | **Deprecated:** Use MCPToolset in the `tools` array instead        |1503| `tool_configuration.enabled`       | boolean | **Deprecated:** Use `default_config.enabled` in MCPToolset         |1504| `tool_configuration.allowed_tools` | array   | **Deprecated:** Use allowlist pattern with `configs` in MCPToolset |1505
Files main
Menu

Theme