Integrate OpenAI Agents with MCP

Introduction

The OpenAI Agents SDK allows developers to build AI agents with instructions, tools, guardrails, handoffs, and runtime orchestration. It uses the OpenAI Responses API by default for OpenAI models.

The Model Context Protocol MCP allows AI applications to connect with external tools and data sources in a standard way. OpenAI’s Agents SDK supports MCP integration, so an OpenAI agent can use tools exposed by an MCP server.

In this post, we will integrate an OpenAI Agent with a simple Python MCP server.


What We Will Build

User Query

OpenAI Agent

MCP Client

Python MCP Server

Tools / Data

Our MCP server will provide two tools:

  1. add_numbers
  2. get_student_details

The OpenAI Agent will call these tools automatically when required.


Step 1: Install Requirements

Create a project folder:

mkdir openai-agent-mcp
cd openai-agent-mcp

Create virtual environment:

python -m venv venv

Activate it:

venv\Scripts\activate

For macOS/Linux:

source venv/bin/activate

Install packages:

pip install openai-agents mcp python-dotenv

Step 2: Create .env File

Create a file named .env:

OPENAI_API_KEY=your_openai_api_key_here

Never hard-code API keys directly inside Python files.


Step 3: Create MCP Server

Create a file named mcp_server.py.

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Student MCP Server")


@mcp.tool()
def add_numbers(a: int, b: int) -> int:
"""
Add two numbers and return the result.
"""
return a + b


@mcp.tool()
def get_student_details(roll_no: int) -> dict:
"""
Return student details using roll number.
"""

students = {
101: {
"name": "Amit Sharma",
"course": "MCA",
"semester": 2
},
102: {
"name": "Neha Verma",
"course": "BCA",
"semester": 4
},
103: {
"name": "Ravi Kumar",
"course": "MCA",
"semester": 1
}
}

return students.get(
roll_no,
{"error": "Student not found"}
)


if __name__ == "__main__":
mcp.run()

This MCP server exposes Python functions as tools using @mcp.tool().


Step 4: Create OpenAI Agent Client

Create another file named agent_client.py.

import asyncio
from dotenv import load_dotenv

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

load_dotenv()


async def main():

async with MCPServerStdio(
params={
"command": "python",
"args": ["mcp_server.py"]
}
) as mcp_server:

agent = Agent(
name="College Assistant",
instructions="""
You are a helpful academic assistant.
Use MCP tools when the user asks for calculations
or student information.
""",
mcp_servers=[mcp_server]
)

result = await Runner.run(
agent,
"Find the details of student with roll number 101."
)

print(result.final_output)


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

Step 5: Run the Agent

Run:

python agent_client.py

Expected output:

The student with roll number 101 is Amit Sharma.
Course: MCA
Semester: 2

The OpenAI Agent receives the user query, discovers the MCP tool, calls it, and returns the final response.


Step 6: Test Another Query

Change the prompt:

result = await Runner.run(
agent,
"Add 45 and 67 using the available tool."
)

Expected output:

45 + 67 = 112

How the Integration Works

The OpenAI Agents SDK defines an agent as an LLM configured with instructions, tools, guardrails, handoffs, and runtime behavior.

In this example:

mcp_servers=[mcp_server]

connects the OpenAI Agent with the MCP server.

The MCP server exposes tools, and the agent can use them when needed.


MCP Server Through Stdio

In this tutorial, we used:

MCPServerStdio

This means the agent starts the MCP server as a local subprocess and communicates with it through standard input/output. The OpenAI Agents SDK documentation explains that MCP servers can be connected by spawning a subprocess or opening a network connection.


Project Structure

openai-agent-mcp/

├── .env
├── mcp_server.py
├── agent_client.py
└── venv/

Why Use OpenAI Agents with MCP?

1. Tool Discovery

The agent can discover tools exposed by the MCP server.

2. Cleaner Architecture

Business logic stays inside the MCP server.

3. Reusability

The same MCP server can be used by different AI agents.

4. Safer Tool Access

You can restrict what the agent can access.

5. Better Agentic Applications

MCP is useful for building agents that access files, databases, APIs, and enterprise tools.


Example Use Cases

You can integrate OpenAI Agents with MCP for:

  • Student record assistants
  • Database query assistants
  • Cloud monitoring agents
  • Code review agents
  • Academic helpdesk bots
  • Placement preparation bots
  • Report generation systems

Security Best Practices

When connecting OpenAI Agents with MCP:

  1. Do not expose dangerous functions such as eval, exec, or unrestricted shell commands.
  2. Use read-only database users where possible.
  3. Add allowlists for tools and tables.
  4. Keep API keys in .env files.
  5. Log tool calls for auditing.
  6. Add human approval for sensitive actions.

The OpenAI Agents SDK supports human-in-the-loop workflows where execution can pause until a person approves or rejects sensitive tool calls.


Common Errors

Error: OpenAI API Key Missing

Check your .env file:

OPENAI_API_KEY=your_key_here

Error: MCP Server Not Found

Make sure mcp_server.py exists in the same folder.

Error: Package Not Found

Run:

pip install openai-agents mcp python-dotenv

Error: Python Command Not Working

Try replacing:

"command": "python"

with:

"command": "python3"

on macOS/Linux.


Conclusion

In this tutorial, we integrated an OpenAI Agent with an MCP server using Python. The MCP server exposed tools, and the OpenAI Agent used those tools to answer user queries.

This architecture is powerful because it separates AI reasoning from external system access. The agent handles conversation and decision-making, while the MCP server safely exposes tools, data, and services.

For modern AI application development, learning OpenAI Agents + MCP is highly useful.


Further Reading

What is MCP? A Beginner’s Guide with Python Examples

MCP vs REST API – Key Differences

Build Your First MCP Server in Python

Create an MCP Server for MySQL Database

Integrate OpenAI Agents with MCP

Security Risks in MCP Servers and How to Mitigate Them

What is n8n? A Beginner-Friendly Guide to Workflow Automation

How to Automatically Publish Blog Posts Using n8n (Step-by-Step Guide)

Top 10 Real-World Use Cases of n8n for Developers

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

Leave a Reply

Your email address will not be published. Required fields are marked *