OpenAI Agents + MCP: Code Examples and Integration Patterns

July 10, 2026 · 11 min read

MCPOpenAIPythonCode
Some links below are affiliate links. I may earn a commission at no extra cost to you.

Introduction

The OpenAI Agents SDK supports MCP servers natively through the agents.mcp module. This means you can connect your agents to any MCP server — filesystem, GitHub, PostgreSQL, Slack, or custom ones — and they'll automatically discover and use the available tools.

This guide provides copy-paste-ready code patterns for the most common integration scenarios.

Pattern 1: Single MCP Server with Filesystem

The simplest integration: one agent, one MCP server.

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

async def main():
    async with MCPServerStdio(
        name="Filesystem",
        params={"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "./data"]}
    ) as server:
        agent = Agent(
            name="File Assistant",
            instructions="You can read and list files. Help the user manage their documents.",
            mcp_servers=[server]
        )
        result = await Runner.run(agent, "List all markdown files and summarize each one")
        print(result.final_output)

asyncio.run(main())

Pattern 2: Multiple MCP Servers

Combine filesystem and fetch servers for a research assistant that can read local files AND fetch web content:

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

async def main():
    async with MCPServerStdio(name="FS", params={"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}) as fs:
        async with MCPServerStdio(name="Fetch", params={"command": "npx", "args": ["-y", "@modelcontextprotocol/server-fetch"]}) as fetch:
            agent = Agent(
                name="Research Assistant",
                instructions="You can read local files and fetch web pages to answer questions.",
                mcp_servers=[fs, fetch]
            )
            result = await Runner.run(agent, "Read the README.md and check if the latest version is on GitHub")
            print(result.final_output)

asyncio.run(main())

Pattern 3: MCP + Custom Python Tools

MCP servers and Python function tools can coexist:

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

@function_tool
def calculate(expression: str) -> float:
    """Evaluate a mathematical expression."""
    return eval(expression)

async def main():
    async with MCPServerStdio(name="FS", params={"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}) as server:
        agent = Agent(
            name="Hybrid Agent",
            instructions="Use filesystem tools for file operations and the calculator for math.",
            tools=[calculate],
            mcp_servers=[server]
        )
        result = await Runner.run(agent, "Read budget.csv and calculate the total")
        print(result.final_output)

asyncio.run(main())

Pattern 4: Error Handling with MCP Servers

MCP servers can fail or timeout. Always handle errors gracefully:

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

async def run_with_fallback():
    try:
        async with MCPServerStdio(name="Fetch", params={"command": "npx", "args": ["-y", "@modelcontextprotocol/server-fetch"]}) as server:
            agent = Agent(
                name="Web Agent",
                instructions="Fetch web pages to answer questions.",
                mcp_servers=[server]
            )
            result = await Runner.run(agent, "What's the latest news about AI?")
            return result.final_output
    except Exception as e:
        return f"Could not start MCP server: {e}"

result = asyncio.run(run_with_fallback())
print(result)

Pattern 5: Programmatic Config (YAML-Free)

Set up multiple MCP servers without a config file:

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

SERVERS = [
    ("Filesystem", "npx", ["-y", "@modelcontextprotocol/server-filesystem", "."]),
    ("GitHub", "npx", ["-y", "@modelcontextprotocol/server-github"]),
    ("Fetch", "npx", ["-y", "@modelcontextprotocol/server-fetch"]),
]

async def main():
    servers = [MCPServerStdio(name=n, params={"command": c, "args": a}) for n, c, a in SERVERS]
    async with servers[0] as s0, servers[1] as s1, servers[2] as s2:
        agent = Agent(
            name="Power Agent",
            instructions="You have filesystem, GitHub, and web access.",
            mcp_servers=[s0, s1, s2]
        )
        result = await Runner.run(agent, "Find todos in my project and create GitHub issues for them")
        print(result.final_output)

asyncio.run(main())

Pattern 6: Remote MCP Server via HTTP

Connect to remote MCP servers over HTTP/SSE:

from agents.mcp import MCPServerHttp

server = MCPServerHttp(
    name="Remote API",
    url="https://my-mcp-server.example.com/sse"
)
# Then pass to Agent mcp_servers as usual

Debugging Tips

Where to Go Next

For a complete walkthrough of MCP concepts, see our MCP + OpenAI Agents guide. For server setup, check MCP servers guide. For architecture deep dive, read MCP architecture overview.

This article contains affiliate links. I may earn a commission at no extra cost to you.