# How to use MCP with OpenAI Agents SDK

- Tool: MCP
- Difficulty: Intermediate
- Time required: 15 min
- Compatibility: OpenAI Agents SDK (Python), any MCP server
- Last updated: March 2026

## TL;DR

The OpenAI Agents SDK added MCP support, letting you connect any MCP server as a tool provider for OpenAI-powered agents. Use the MCPServerStdio or MCPServerStreamableHttp class to connect to servers, then pass them to your Agent definition. The SDK converts MCP tools into OpenAI function calling format automatically. This lets you use the same MCP servers across OpenAI agents, Claude Desktop, Cursor, and other hosts.

## Connect MCP Servers to OpenAI Agents

OpenAI's Agents SDK includes built-in MCP client support, bridging the gap between the MCP ecosystem and OpenAI models. You can connect any MCP server to an OpenAI agent, and the SDK automatically converts MCP tools into OpenAI's function calling format. This means the same MCP server you use with Claude Desktop or Cursor also works with GPT-4o-powered agents. This tutorial covers both local (stdio) and remote (HTTP) server connections.

## Before you start

- Python 3.10+ installed
- OpenAI Agents SDK installed (pip install openai-agents)
- An OpenAI API key
- An MCP server to connect (npm package, local server, or Docker)

## Step-by-step guide

### 1. Install the OpenAI Agents SDK with MCP support

Install the OpenAI Agents SDK which includes MCP client classes. The SDK provides MCPServerStdio for local stdio servers and MCPServerStreamableHttp for remote HTTP servers. Also install the MCP Python SDK if you want to build servers.

```
pip install openai-agents

# Optional: MCP Python SDK for building servers
pip install "mcp[cli]"
```

**Expected result:** The openai-agents package is installed with MCP support included.

### 2. Connect a local MCP server using MCPServerStdio

Use MCPServerStdio to connect to a local MCP server that communicates via stdio. Pass the command and arguments as a list. The SDK launches the server process, performs the MCP handshake, and discovers available tools. Use it as an async context manager to ensure proper cleanup.

```
from agents.mcp import MCPServerStdio

# Create the server connection
async with MCPServerStdio(
    command="npx",
    args=["-y", "@modelcontextprotocol/server-filesystem", "/Users/you/projects"],
) as server:
    # server is now connected and tools are discovered
    tools = await server.list_tools()
    print(f"Available tools: {[t.name for t in tools]}")
```

**Expected result:** The MCP server is connected and its tools are discovered.

### 3. Create an agent that uses MCP tools

Pass the connected MCP server to an Agent definition using the mcp_servers parameter. The SDK converts MCP tools to OpenAI function calling format automatically. The agent can then use these tools during its reasoning process just like native function calls.

```
from agents import Agent, Runner
from agents.mcp import MCPServerStdio

async def main():
    async with MCPServerStdio(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-filesystem", "/Users/you/projects"],
    ) as filesystem_server:

        agent = Agent(
            name="file-assistant",
            instructions="You help users explore and understand their project files.",
            mcp_servers=[filesystem_server],
        )

        result = await Runner.run(
            agent,
            "What TypeScript files are in the src directory?",
        )
        print(result.final_output)

import asyncio
asyncio.run(main())
```

**Expected result:** The agent uses the filesystem MCP server to list TypeScript files and returns a natural language answer.

### 4. Connect a remote MCP server via HTTP

For remote MCP servers running on another machine or cloud, use MCPServerStreamableHttp. This connects to the server's HTTP endpoint instead of launching a local process. This is useful for shared team servers or cloud-deployed MCP services.

```
from agents.mcp import MCPServerStreamableHttp

async with MCPServerStreamableHttp(
    url="https://mcp.your-company.com/api",
    headers={"Authorization": "Bearer your-token"},
) as remote_server:
    agent = Agent(
        name="remote-assistant",
        instructions="You help users with remote data.",
        mcp_servers=[remote_server],
    )
    result = await Runner.run(agent, "What is the latest data?")
    print(result.final_output)
```

**Expected result:** The agent connects to the remote MCP server over HTTP and uses its tools.

### 5. Combine multiple MCP servers in one agent

Pass multiple MCP servers to a single agent. The agent can use tools from all connected servers during its reasoning. This is powerful for building agents that combine data from different sources — for example, reading files with the filesystem server while searching the web with Brave Search.

```
from agents import Agent, Runner
from agents.mcp import MCPServerStdio

async def main():
    async with MCPServerStdio(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-filesystem", "/Users/you/projects"],
    ) as fs_server, MCPServerStdio(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-brave-search"],
        env={"BRAVE_API_KEY": "your-key"},
    ) as search_server:

        agent = Agent(
            name="research-assistant",
            instructions="You help users research topics using their files and the web.",
            mcp_servers=[fs_server, search_server],
        )

        result = await Runner.run(
            agent,
            "Read my project's README and search the web for similar projects.",
        )
        print(result.final_output)

import asyncio
asyncio.run(main())
```

**Expected result:** The agent uses tools from both MCP servers to complete the research task.

### 6. Pass environment variables to MCP servers

Use the env parameter to pass environment variables (API keys, database URLs) to MCP servers. This works with both MCPServerStdio and MCPServerStreamableHttp. For teams building complex multi-server agent architectures, RapidDev can help design and implement the MCP integration layer.

```
from agents.mcp import MCPServerStdio

async with MCPServerStdio(
    command="npx",
    args=["-y", "@modelcontextprotocol/server-postgres"],
    env={
        "POSTGRES_CONNECTION_STRING": "postgresql://user:pass@localhost:5432/mydb",
    },
) as db_server:
    # db_server tools are now available
    pass
```

**Expected result:** The MCP server receives environment variables for authentication and configuration.

## Complete code example

File: `agent_with_mcp.py`

```python
"""OpenAI Agent with MCP server integration.

Run: python agent_with_mcp.py
Requires: pip install openai-agents
Requires: OPENAI_API_KEY environment variable
"""

import asyncio
import os
from agents import Agent, Runner
from agents.mcp import MCPServerStdio


async def main():
    # Connect to the filesystem MCP server
    async with MCPServerStdio(
        command="npx",
        args=[
            "-y",
            "@modelcontextprotocol/server-filesystem",
            os.path.expanduser("~/projects"),
        ],
    ) as filesystem_server:

        # Create an agent with MCP tools
        agent = Agent(
            name="project-explorer",
            instructions=(
                "You are a helpful assistant that explores project files. "
                "When asked about files, use the filesystem tools to read "
                "and list files. Provide concise summaries of what you find."
            ),
            mcp_servers=[filesystem_server],
        )

        # Run the agent with a user query
        result = await Runner.run(
            agent,
            "List the top-level files and directories in my projects folder. "
            "For any README.md files you find, give me a one-sentence summary.",
        )

        print("Agent response:")
        print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())
```

## Common mistakes

- **Not using async with for MCP server connections** — undefined Fix: MCP server connections must be used as async context managers (async with). This ensures proper initialization, cleanup, and process termination. Forgetting async with leads to leaked processes.
- **Forgetting to set the OPENAI_API_KEY environment variable** — undefined Fix: The Agents SDK requires a valid OpenAI API key. Set it as an environment variable: export OPENAI_API_KEY=sk-your-key. Without it, agent runs fail with authentication errors.
- **Using MCPServerStreamableHttp for local servers** — undefined Fix: Use MCPServerStdio for local servers launched as child processes. MCPServerStreamableHttp is for remote servers running on a separate machine. Using the wrong transport class causes connection failures.
- **Not passing -y in npx args** — undefined Fix: When using npx in MCPServerStdio args, always include '-y' as the first argument to prevent installation prompts that would hang the process.

## Best practices

- Always use async with for MCP server connections to ensure proper cleanup
- Pass environment variables via the env parameter rather than relying on shell environment
- Combine MCP servers with native Agent tools for maximum capability
- Test MCP servers independently with MCP Inspector before integrating with agents
- Use MCPServerStdio for local servers and MCPServerStreamableHttp for remote ones
- Set timeouts on agent runs to prevent hanging when MCP servers are slow
- Include -y in all npx commands to prevent interactive prompts
- Log MCP tool calls during development to debug agent reasoning

## Frequently asked questions

### Does this work with GPT-4o and other OpenAI models?

Yes. The Agents SDK converts MCP tools into OpenAI's function calling format, which works with GPT-4o, GPT-4o-mini, and other function-calling-capable models. The MCP server does not know or care which model is calling it.

### Can I mix MCP tools with native Agent tools?

Yes. An Agent can have both mcp_servers and native tools defined. The SDK combines all available tools and presents them to the model for selection during reasoning.

### Is the OpenAI Agents SDK free?

The SDK itself is free and open source. You pay for OpenAI API usage when running agents. MCP servers themselves are free — there is no additional cost for MCP integration.

### Can I use TypeScript MCP servers with the Python Agents SDK?

Yes. MCPServerStdio launches any command as a child process. TypeScript servers run via npx or node, Python servers via python or uv. The SDK communicates with them via the MCP protocol regardless of the server's language.

### Can RapidDev help build agent workflows with MCP?

Yes. RapidDev helps teams design and build multi-agent systems that leverage MCP servers for data access, tool execution, and workflow automation. We specialize in connecting internal tools to AI agents via MCP.

---

Source: https://www.rapidevelopers.com/mcp-tutorial/how-to-use-mcp-with-openai-agents-sdk
© RapidDev — https://www.rapidevelopers.com/mcp-tutorial/how-to-use-mcp-with-openai-agents-sdk
