---
title: Call MCP tools from a Python agent
description: Use MCP tools from a Python agent with LangGraph, the OpenAI Agents SDK, or the OpenAI client. Sign in, discover tools, and make a first call.
canonical_url: https://docs.databricks.com/aws/en/agents/custom-agents/use-mcp-tools
---

# Call MCP tools from a Python agent

Use MCP tools in a custom Python agent built with LangGraph, the OpenAI Agents SDK, or the OpenAI client. The examples show how to sign in, discover tools, and run an agent locally with your own Databricks credentials.

For an app that calls tools on behalf of signed-in users, see [Connect your app to MCP tools](https://docs.databricks.com/aws/en/agents/custom-agents/use-mcp-tools-in-app.md).

For other ways to connect, see [Supported coding and work agents](https://docs.databricks.com/aws/en/ai-gateway/coding-agent-supported-agents.md), [Other MCP clients](https://docs.databricks.com/aws/en/ai-gateway/coding-agent-mcp-skills.md#other-mcp-clients), or [Add MCP tools with the Agent Bricks CLI](https://docs.databricks.com/aws/en/agents/custom-agents/agent-bricks-cli.md#add-mcp-tools).

## <a id="before-you-start" />Prerequisites

* Python 3.12 on your computer.
* The URL of a [Databricks-provided MCP](https://docs.databricks.com/aws/en/agents/mcp-tools/built-in-mcp-services.md), [registered MCP](https://docs.databricks.com/aws/en/ai-gateway/register-mcp-service.md), or [server on Databricks Apps](https://docs.databricks.com/aws/en/agents/mcp-tools/custom-mcp.md). If someone shared an MCP with you, they must [grant you access](https://docs.databricks.com/aws/en/ai-gateway/govern-mcp-service.md#control-callers). Complete the [provider sign-in](https://docs.databricks.com/aws/en/ai-gateway/mcp-service-reference.md#provider-sign-in) if it uses per-user OAuth. For a server on Databricks Apps, you need **CAN USE** on the app.
* To use a [workspace MCP endpoint](https://docs.databricks.com/aws/en/agents/mcp-tools/built-in-mcp-services.md#legacy-workspace-endpoints), a workspace admin must enable **Managed MCP Servers** on the workspace [Previews page](https://docs.databricks.com/aws/en/admin/workspace-settings/manage-previews.md#workspace).
* Access to a Databricks [model endpoint that supports tool calling](https://docs.databricks.com/aws/en/machine-learning/model-serving/function-calling.md). The example uses `databricks-claude-sonnet-4-5`. Replace it with an endpoint available in your workspace.

`system.ai.dbsql`, `system.ai.sandbox`, and `system.ai.web_search` are in [Beta](https://docs.databricks.com/aws/en/release-notes/release-types.md). To use them, an account admin must enable the **Enhanced Unity Gateway** preview from the account console **Previews** page. Unity Gateway itself is generally available. See [Manage account previews](https://docs.databricks.com/aws/en/admin/workspace-settings/manage-previews.md#account).

For identity choices, see [Supported outbound authentication](https://docs.databricks.com/aws/en/agents/mcp-tools/authentication-networking.md#choose). For connectivity requirements, see [MCP networking](https://docs.databricks.com/aws/en/agents/mcp-tools/networking.md).

<a id="1-install-and-sign-in" />

## <a id="set-up-your-environment" />Step 1: Install and sign in

1. If you haven't installed the Databricks CLI, run this command on macOS or Linux:

   ```bash
   curl -fsSL https://raw.githubusercontent.com/databricks/setup-cli/main/install.sh | sh
   ```

   For Windows or other installation methods, see [Install the Databricks CLI](https://docs.databricks.com/aws/en/dev-tools/cli/install.md).

2. Sign in to your workspace:

   ```bash
   databricks auth login --host https://<workspace-hostname> --profile DEFAULT
   ```

3. Install the Python libraries:

   ```bash
   pip install --upgrade databricks-mcp databricks-sdk "mcp>=1.24,<2"
   ```

The examples use MCP Python 1.x, which is compatible with the agent frameworks below.

<a id="2-connect-to-your-server" />

## <a id="connect-and-list-tools" />Step 2: Connect to your server

<a id="get-your-server-url" />

Save the following code as `mcp_agent.py`. Replace `<mcp-server-url>` with your server's URL:

* **Databricks-provided or registered MCP:** `https://<workspace-hostname>/ai-gateway/mcp-services/<catalog>.<schema>.<service>`.
* **Server on Databricks Apps:** Copy the app URL from its overview page and append `/mcp`.
* **[Workspace MCP endpoint](https://docs.databricks.com/aws/en/agents/mcp-tools/built-in-mcp-services.md#legacy-workspace-endpoints):** `https://<workspace-hostname>` followed by one of these paths:
  * Unity Catalog functions: `/api/2.0/mcp/functions/{catalog}/{schema}/{function_name}`
  * AI Search: `/api/2.0/mcp/ai-search/{catalog}/{schema}/{index_name}`
  * Genie Agent: `/api/2.0/mcp/genie/{genie_space_id}`
  * Databricks SQL: `/api/2.0/mcp/sql`

```python
from databricks_mcp import DatabricksMCPClient
from databricks.sdk import WorkspaceClient

workspace_client = WorkspaceClient()
server_url = "<mcp-server-url>"
mcp_client = DatabricksMCPClient(
    server_url=server_url,
    workspace_client=workspace_client,
)

tools = mcp_client.list_tools()
for tool in tools:
    print(tool.name, tool.description, tool.inputSchema, sep="\n")
```

Run the script:

```bash
python mcp_agent.py
```

You should see your server's tools, with descriptions and input schemas. Choose a read-only task that one of these tools supports for the next step. If the list is empty or the connection fails, see [MCP authentication](https://docs.databricks.com/aws/en/agents/mcp-tools/authentication-networking.md).

### <a id="use-another-server" />Use another server

* For a [built-in MCP](https://docs.databricks.com/aws/en/agents/mcp-tools/built-in-mcp-services.md), use its full name in the MCP URL, such as `system.ai.github`.
* For an existing integration with a [workspace MCP server](https://docs.databricks.com/aws/en/agents/mcp-tools/built-in-mcp-services.md#legacy-workspace-endpoints), set `server_url` to one of the [workspace endpoint URLs](https://docs.databricks.com/aws/en/agents/custom-agents/use-mcp-tools.md#get-your-server-url) above.

<a id="discover-available-mcp-servers-and-tools" />

To find MCPs you can access in a catalog and schema, run:

```bash
databricks ai-gateway list-mcp-services --parent schemas/system.ai
```

Replace `system.ai` with your `<catalog>.<schema>` to list registered MCPs. The CLI handles pagination.

<a id="3-run-an-agent-with-these-tools" />

## <a id="build-an-agent" />Step 3: Run an agent with these tools

Choose your framework, install its package, and append its Python example to `mcp_agent.py`. Each example uses the same `server_url` and workspace sign-in from step 2.

<a id="example-notebooks" />

### LangGraph

The example uses a model middleware that converts MCP content blocks to the model's chat message format with `convert_to_openai_messages`.

```bash
pip install --upgrade "databricks-langchain==0.22.0" "langgraph==1.2.20" "mcp>=1.24,<2"
```

```python
import asyncio
from databricks_langchain import (
    ChatDatabricks,
    DatabricksMCPServer,
    DatabricksMultiServerMCPClient,
)
from langchain.agents import create_agent
from langchain.agents.middleware import wrap_model_call
from langchain_core.messages import convert_to_messages, convert_to_openai_messages

@wrap_model_call
async def convert_mcp_content(request, handler):
    messages = convert_to_messages(convert_to_openai_messages(request.messages))
    return await handler(request.override(messages=messages))

async def main():
    client = DatabricksMultiServerMCPClient([
        DatabricksMCPServer(
            name="my-mcp-server",
            url=server_url,
            workspace_client=workspace_client,
        ),
    ])
    agent = create_agent(
        model=ChatDatabricks(endpoint="databricks-claude-sonnet-4-5"),
        tools=await client.get_tools(),
        middleware=[convert_mcp_content],
    )
    task = input("Ask the agent to use a tool: ")
    result = await agent.ainvoke({
        "messages": [{"role": "user", "content": task}],
    })
    for message in result["messages"]:
        print(message)

asyncio.run(main())
```

**Deployment notebook (optional)**

For Model Serving deployment, adapt this notebook to use your server URL:

#### LangGraph MCP tool-calling agent

[Get notebook](https://docs.databricks.com/notebooks/source/generative-ai/langgraph-mcp-tool-calling-agent.html)

### OpenAI Agents SDK

```bash
pip install --upgrade databricks-openai openai-agents
```

```python
import asyncio
from agents import Agent, Runner, set_default_openai_api, set_default_openai_client
from agents.mcp import MCPServerStreamableHttpParams
from agents.tracing import set_trace_processors
from databricks_openai import AsyncDatabricksOpenAI
from databricks_openai.agents.mcp_server import McpServer

set_default_openai_client(AsyncDatabricksOpenAI())
set_default_openai_api("chat_completions")
set_trace_processors([])

async def main():
    async with McpServer(
        name="my-mcp-server",
        params=MCPServerStreamableHttpParams(url=server_url),
        workspace_client=workspace_client,
    ) as server:
        agent = Agent(
            name="Tool-using agent",
            instructions="Use the available tools to answer the user's question.",
            model="databricks-claude-sonnet-4-5",
            mcp_servers=[server],
        )
        task = input("Ask the agent to use a tool: ")
        result = await Runner.run(agent, task)
        for item in result.new_items:
            print(item.to_input_item())

asyncio.run(main())
```

**Deployment notebook (optional)**

For Model Serving deployment, adapt this notebook to use your server URL:

#### Agents SDK MCP tool-calling agent

[Get notebook](https://docs.databricks.com/notebooks/source/generative-ai/agents-sdk-mcp-tool-calling-agent.html)

### OpenAI client

```bash
pip install --upgrade databricks-openai
```

This example runs the tool-calling loop explicitly using the OpenAI-compatible client.

```python
import json
from databricks_openai import DatabricksOpenAI, McpServerToolkit

toolkit = McpServerToolkit(url=server_url, workspace_client=workspace_client)
tools_by_name = {tool.name: tool for tool in toolkit.get_tools()}
model_client = DatabricksOpenAI()
messages = [{"role": "user", "content": input("Ask the agent to use a tool: ")}]

for _ in range(10):
    response = model_client.chat.completions.create(
        model="databricks-claude-sonnet-4-5",
        messages=messages,
        tools=[tool.spec for tool in tools_by_name.values()],
    )
    message = response.choices[0].message
    messages.append(message.model_dump(exclude_none=True))
    if not message.tool_calls:
        print(message.content)
        break
    for call in message.tool_calls:
        try:
            tool = tools_by_name.get(call.function.name)
            if tool is None:
                raise ValueError(f"Unknown tool: {call.function.name}")
            arguments = json.loads(call.function.arguments or "{}")
            if not isinstance(arguments, dict):
                raise ValueError("Tool arguments must be a JSON object.")
            output = tool.execute(**arguments)
        except Exception as error:
            output = json.dumps({"error": str(error)})
        print(call.function.name, output)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": str(output),
        })
else:
    raise RuntimeError("The agent reached the tool-calling limit.")
```

**Deployment notebook (optional)**

For Model Serving deployment, adapt this notebook to use your server URL:

#### OpenAI MCP tool-calling agent

[Get notebook](https://docs.databricks.com/notebooks/source/generative-ai/openai-mcp-tool-calling-agent.html)

Run `python mcp_agent.py` again. When prompted, ask for the read-only task you chose, including any required inputs. For example, if your server has a ticket search tool, ask it to find open tickets in a specific project.

Check the printed conversation for a tool call, its result, and the agent's answer. An answer without a tool call doesn't confirm that the MCP server was used.

### <a id="call-a-tool-directly" />Call a tool directly to troubleshoot

Use the tool name and input schema printed in step 2. This example prompts for the name and arguments so it works with your server's tools. Run it after the connection code in step 2:

```python
import json

tool_name = input("Read-only tool name: ")
arguments = json.loads(input("Tool arguments as a JSON object: "))
result = mcp_client.call_tool(tool_name, arguments)
print(result)
```

Check that the result has no tool error and contains the data you expected.

<a id="discover-tools" />

Discover tool names and input schemas with `list_tools()` before calling a tool. Result formats vary by tool:

* If `structuredContent` is present, use that structured result directly. A tool can describe its shape with `outputSchema`.
* Otherwise, inspect the `content` blocks. Parse a text block as JSON only if the tool returns JSON. MCP also supports plain text and other content types.
* Check `isError` and inspect a sample response before relying on particular output fields.

## <a id="authenticate" />Deploy and share when you're ready

<a id="deploy-your-agent" />

The local example runs as you. When you [deploy the agent on Databricks Apps](https://docs.databricks.com/aws/en/agents/custom-agents/author-agent.md), [choose the identity it uses](https://docs.databricks.com/aws/en/agents/custom-agents/agent-authentication.md): the app's service principal for shared access, or the calling user for per-user access.

For Databricks-provided or registered MCPs:

* [Grant the caller access](https://docs.databricks.com/aws/en/ai-gateway/govern-mcp-service.md#control-callers) to the MCP and its parent catalog and schema.
* [Configure per-user access](https://docs.databricks.com/aws/en/agents/custom-agents/agent-authentication.md#authenticate-to-mcp-services) if your agent acts on behalf of a user. If your app signs users in with your own identity provider, see [Connect your app to MCP tools](https://docs.databricks.com/aws/en/agents/custom-agents/use-mcp-tools-in-app.md).
* [Govern the MCP](https://docs.databricks.com/aws/en/ai-gateway/govern-mcp-service.md) to restrict tools, apply policies, set rate limits, and monitor calls.

For workspace MCP endpoints or servers hosted on Databricks Apps, grant access to the underlying resources or app. See [Agent authentication](https://docs.databricks.com/aws/en/agents/custom-agents/agent-authentication.md).

## Additional resources

* [Deploy an agent on Model Serving](https://docs.databricks.com/aws/en/agents/custom-agents/model-serving/deploy-agent.md).
* [Configure authentication for Model Serving agents](https://docs.databricks.com/aws/en/agents/custom-agents/model-serving/agent-authentication-model-serving.md).
