DEV Community

The Worthy Son
The Worthy Son

Posted on Originally published at theworthysonmedia.blogspot.com on

How to Build Your First AI Agent Using Model Context Protocol and Python

Building an AI agent involves more than connecting a language model to a chatbot interface. A useful agent needs access to external tools, the ability to process information, and a controlled way to perform tasks on behalf of a user.

For example, an AI agent could calculate figures, retrieve information from a local database, read documents, create reports, or interact with external services. However, giving an AI model access to these capabilities introduces an important technical challenge: how do you connect the model to external tools without building a separate integration for every application?

The Model Context Protocol (MCP) provides a standard approach to this problem.

MCP allows AI applications to communicate with external tools and data sources through a common protocol. Instead of building a different connection for every model and application, developers can create MCP servers that expose specific capabilities to compatible AI clients.

Python makes this process accessible to beginners because the official MCP Python SDK provides tools for creating servers, registering functions, and connecting clients.

This tutorial explains how to build a basic AI agent using Python and MCP. You will create an MCP server, register tools, connect the server to an AI agent, and introduce safeguards that control which actions the agent can perform.

By the end, you will have a practical foundation for developing more advanced AI agents.

1. Understanding Model Context Protocol

Before writing code, it is important to understand what MCP does and how its components work together.

The Model Context Protocol is an open protocol that standardizes communication between AI applications and external systems.

Consider a situation in which you want an AI assistant to access a calculator, retrieve information from a database, and create a document.

Without a standardized connection, you would need to implement separate integrations for these services. MCP provides a common communication method that allows compatible applications to discover and use tools exposed by MCP servers.

Three components are particularly important:

MCP Host: This is the AI application that the user interacts with. It could be an AI assistant, an integrated development environment, or a custom agent application.

MCP Client: This component operates within the host. It communicates with MCP servers, discovers available capabilities, and sends requests to execute tools.

MCP Server: This is the application you build. It exposes tools, resources, and prompts that compatible clients can access.

MCP also defines three main types of capabilities:

  • Tools: Functions that an AI model can call to perform actions, such as calculations, database operations, or API requests.

  • Resources: Data that an application can retrieve and provide to an AI model as context.

  • Prompts: Reusable message templates that users or applications can invoke.

These capabilities have different purposes. Tools can execute operations, resources provide information, and prompts help structure interactions.

An important distinction is that an MCP server does not automatically become an AI agent. The server provides access to external capabilities. The host or agent runtime connects those capabilities to a language model and manages the interaction.

For this tutorial, you will use the official MCP Python SDK to build the server and the OpenAI Agents SDK to connect it to an AI agent.

2. Preparing Your Python Development Environment

You need a working Python installation and a few development tools.

The current official MCP Python SDK v2 requires Python 3.11 or later. The examples in this tutorial use the v2 API, which differs from the older v1 API.

Install the following:

  • Python 3.11 or later.

  • A code editor, such as Visual Studio Code.

  • uv, a Python project and package manager.

  • An OpenAI API key.

  • Access to a terminal or command prompt.

You can check your Python installation by running:

python --version
Enter fullscreen mode Exit fullscreen mode

The output should indicate Python 3.11 or a later version.

Next, install uv if it is not already available. Follow the installation instructions in the official uv documentation.

Create a project directory:

mkdir first-mcp-agent
cd first-mcp-agent
Enter fullscreen mode Exit fullscreen mode

Initialize a Python project:

uv init --bare
Enter fullscreen mode Exit fullscreen mode

Install the MCP Python SDK and its command-line tools:

uv add "mcp[cli]>=2,<3"
Enter fullscreen mode Exit fullscreen mode

Install the OpenAI Agents SDK:

uv add openai-agents
Enter fullscreen mode Exit fullscreen mode

These packages serve different purposes.

The MCP SDK allows your application to create and operate MCP servers. The OpenAI Agents SDK provides the agent runtime, connects the model to available tools, and manages tool execution.

You now have the basic dependencies required for the project.

3. Creating Your First MCP Server

The next step is to create an MCP server that exposes Python functions as tools.

Create a file named:

server.py
Enter fullscreen mode Exit fullscreen mode

Inside this file, add the following code:

from mcp.server import MCPServer# Create the MCP servermcp = MCPServer("My First MCP Server")@mcp.tool()def add_numbers(a: float, b: float) -> float: """Add two numbers and return the result.""" return a + b@mcp.tool()def multiply_numbers(a: float, b: float) -> float: """Multiply two numbers and return the result.""" return a * b@mcp.tool()def get_greeting(name: str) -> str: """Return a greeting for the supplied name.""" return f"Hello, {name}! Your MCP server is working."if __name__ == " __main__": mcp.run()
Enter fullscreen mode Exit fullscreen mode

This is your first MCP server.

Let's examine the important parts.

The first line imports MCPServer from the official Python SDK:

from mcp.server import MCPServer
Enter fullscreen mode Exit fullscreen mode

You then create an instance:

mcp = MCPServer("My First MCP Server")
Enter fullscreen mode Exit fullscreen mode

The name identifies your server to connecting clients.

The @mcp.tool() decorator registers a Python function as an MCP tool.

For example:

@mcp.tool()def add_numbers(a: float, b: float) -> float: return a + b
Enter fullscreen mode Exit fullscreen mode

This function accepts two numerical arguments and returns their sum.

The SDK uses the function's name, documentation string, and type annotations to describe the tool and its expected arguments.

This means you do not have to manually write a separate tool definition for this simple example.

The same process applies to the multiplication and greeting functions.

Finally:

if __name__ == " __main__": mcp.run()
Enter fullscreen mode Exit fullscreen mode

starts the server.

When no transport is specified, the SDK uses standard input and standard output (stdio). This is useful when an MCP host launches the server as a local subprocess.

Your server now exposes three tools:

  1. add_numbers

  2. multiply_numbers

  3. get_greeting

The server does not independently decide when to call these functions. A compatible client discovers the tools and can request their execution.

4. Testing Your MCP Server

Before connecting an AI agent, test the server independently.

The official MCP Python SDK includes the MCP Inspector, a development tool that allows you to inspect servers, discover registered tools, and test their execution.

Run:

uv run mcp dev server.py
Enter fullscreen mode Exit fullscreen mode

The command starts the development server and provides access to the MCP Inspector.

Open the address displayed in your terminal.

You should be able to locate the three registered tools:

  • add_numbers

  • multiply_numbers

  • get_greeting

Test the addition function with:

{
  "a": 15,
  "b": 25
}
Enter fullscreen mode Exit fullscreen mode

The expected result is:

{
  "result": 40
}
Enter fullscreen mode Exit fullscreen mode

Test the multiplication function:

{
  "a": 8,
  "b": 5
}
Enter fullscreen mode Exit fullscreen mode

The expected result is:

{
  "result": 40
}
Enter fullscreen mode Exit fullscreen mode

Finally, test the greeting function:

{
  "name": "Developer"
}
Enter fullscreen mode Exit fullscreen mode

The server should return:

Hello, Developer! Your MCP server is working.
Enter fullscreen mode Exit fullscreen mode

If these tests succeed, your server is exposing its tools correctly.

Testing at this stage is important. If a tool fails independently, connecting an AI agent will not solve the underlying problem.

5. Connecting Standard Tools to Your AI Agent

Your MCP server now works, but you still need an AI agent that can discover its tools and decide when to use them.

For this tutorial, you will use the OpenAI Agents SDK.

The SDK supports MCP connections through several transports, including stdio and Streamable HTTP.

Since your server runs locally, stdio is a practical choice.

Create another file:

agent.py
Enter fullscreen mode Exit fullscreen mode

Add the following code:

import asynciofrom agents import Agent, Runnerfrom agents.mcp import MCPServerStdioasync def main(): async with MCPServerStdio( name="My First MCP Server", params={ "command": "uv", "args": ["run", "server.py"], }, ) as server: agent = Agent( name="Python MCP Assistant", instructions=""" You are a helpful AI assistant. You can use the tools provided by the connected MCP server. Use the appropriate tool when the user requests a calculation or greeting. Explain the result clearly. Never claim that a tool was executed if it was not successfully executed. """, mcp_servers=[server], )
Enter fullscreen mode Exit fullscreen mode

Here is what happens when this application runs.

First, the agent connects to the MCP server.

async with MCPServerStdio( name="My First MCP Server", params={ "command": "uv", "args": ["run", "server.py"], },) as server:
Enter fullscreen mode Exit fullscreen mode

The MCPServerStdio integration launches your local Python server as a subprocess.

The agent runtime communicates with it through standard input and standard output.

The context manager also manages the connection lifecycle. When execution leaves the async with block, the server connection is closed.

Second, you create the AI agent.

agent = Agent( name="Python MCP Assistant", instructions="You are a helpful AI assistant.", mcp_servers=[server],)
Enter fullscreen mode Exit fullscreen mode

The Agent object receives access to the connected MCP server.

The agent runtime can discover the tools exposed by that server and make them available to the language model.

Third, the agent receives a request.

result = await Runner.run( agent, "Calculate 125 multiplied by 8.")
Enter fullscreen mode Exit fullscreen mode

The model can identify that the multiplication tool is appropriate.

It can then request execution of:

multiply_numbers(125, 8)
Enter fullscreen mode Exit fullscreen mode

The MCP server executes the Python function and returns its result.

The agent uses that result to produce its final response.

The expected numerical result is:

1000
Enter fullscreen mode Exit fullscreen mode

The important point is that the language model does not need to implement the multiplication operation itself. It can request that the MCP tool perform the calculation.

This is the basic relationship between an AI agent, an MCP client, and an MCP server.

6. Allowing the Agent to Execute Actions Safely

Giving an AI agent access to external tools introduces security risks.

A tool might read confidential information, modify files, delete records, or send requests to external services.

A model can also select an inappropriate tool or provide incorrect arguments.

For these reasons, tool access should be controlled.

A useful starting point is to divide tools into two categories.

Read-only tools

These retrieve information without modifying external data.

Examples include:

  • Reading a document.

  • Retrieving database records.

  • Searching a permitted directory.

  • Checking the status of an application.

Action-performing tools

These can change something outside the model's response.

Examples include:

  • Creating a document.

  • Updating a database.

  • Sending an email.

  • Deleting a file.

  • Submitting an external request.

Sensitive operations should require approval.

The OpenAI Agents SDK supports approval policies for local MCP tools.

For example, suppose you add a tool called save_note to your MCP server. You can require approval before that tool executes by configuring the connection as follows:

async with MCPServerStdio( name="My First MCP Server", params={ "command": "uv", "args": ["run", "server.py"], }, require_approval={ "always": { "tool_names": ["save_note"] } },) as server: # Create and run the agent here. ...
Enter fullscreen mode Exit fullscreen mode

The policy requires approval for save_note, while other tools are not automatically subjected to that particular approval requirement.

The agent runtime must handle the approval request through its human-in-the-loop approval workflow. Do not automatically approve sensitive operations merely to make the program run.

For a beginner project, you should follow these security practices:

  1. Give each tool access only to the information and operations it needs.

  2. Require approval before deleting files, sending messages, or modifying important records.

  3. Validate arguments before executing functions.

  4. Keep API keys and passwords outside your source code.

  5. Avoid giving an agent unrestricted access to your computer.

  6. Record important tool executions so that actions can be reviewed.

  7. Return clear errors when an operation fails.

MCP does not automatically enforce every security measure. Developers must implement appropriate authorization, access controls, and approval procedures in their applications.

A tool description is also not a security boundary. A function that claims to be read-only must actually be implemented without unintended write operations.

7. Adding a Tool That Creates a File

To understand how an agent can perform an actual operation, let's extend the server with a tool that creates a text file.

This example uses a dedicated directory rather than allowing the agent to write anywhere on your computer.

Add the following code to server.py:

from pathlib import Pathimport reNOTES_DIR = Path("agent_notes").resolve()NOTES_DIR.mkdir(exist_ok=True)@mcp.tool()def save_note(filename: str, content: str) -> str: """ Save a text note in the approved notes directory. """ # Accept simple filenames only. if not re.fullmatch(r"[A-Za-z0-9_-]{1,50}", filename): raise ValueError("Invalid filename.") if len(content) > 5000: raise ValueError("Note exceeds the allowed length.") file_path = (NOTES_DIR / f"{filename}.txt").resolve() # Prevent writing outside the approved directory. if file_path.parent != NOTES_DIR: raise ValueError("Access outside the notes directory is prohibited.") if file_path.exists(): raise FileExistsError("This note already exists.") file_path.write_text(content, encoding="utf-8") return f"Note successfully saved as {filename}.txt"
Enter fullscreen mode Exit fullscreen mode

This function introduces several safeguards.

Filename validation: The regular expression limits filenames to letters, numbers, underscores, and hyphens.

Content validation: The function rejects content longer than 5,000 characters.

Directory restriction: Files can only be created inside the dedicated agent_notes directory.

Overwrite protection: The function refuses to replace an existing note.

These restrictions reduce the risk of accidental file modification.

Now update your agent's connection configuration to require approval for the file creation tool:

require_approval={ "always": { "tool_names": ["save_note"] }}
Enter fullscreen mode Exit fullscreen mode

When the agent requests this operation, the runtime must obtain approval before allowing execution.

A request such as:

Create a note named project_plan containing:
Build a Python AI agent using MCP.
Enter fullscreen mode Exit fullscreen mode

can result in the agent preparing a call to save_note.

The approval workflow must allow the user or authorized reviewer to inspect and approve that operation before the server writes the file.

This distinction matters. The AI model proposes the operation, but the application controls whether it is authorized to execute.

For production applications, additional protections may include file size limits, quotas, access permissions, audit logs, and restrictions on the content that can be written.

8. Configuring Your OpenAI API Key

Your agent also needs access to an OpenAI model.

Create an API key through the official OpenAI developer platform.

Do not paste the key directly into agent.py or server.py.

Instead, store it as an environment variable.

On Linux or macOS, run:

export OPENAI_API_KEY="your_api_key"
Enter fullscreen mode Exit fullscreen mode

On Windows PowerShell, run:

$env:OPENAI_API_KEY="your_api_key"
Enter fullscreen mode Exit fullscreen mode

The OpenAI Agents SDK uses the configured API key to authenticate requests.

Keep the key private. Do not commit it to a public Git repository, include it in screenshots, or expose it through application logs.

If you are developing a larger application, use a secure secrets-management system rather than relying on manually configured terminal variables.

9. Running Your First AI Agent

Your project directory should now contain:

first-mcp-agent/
│
├── server.py
├── agent.py
├── pyproject.toml
└── agent_notes/
Enter fullscreen mode Exit fullscreen mode

You can run the agent from your project directory:

uv run python agent.py
Enter fullscreen mode Exit fullscreen mode

The application should:

  1. Start the MCP server as a local subprocess.

  2. Establish the MCP connection.

  3. Discover the server's available tools.

  4. Pass the available tools to the AI agent.

  5. Send the user's request to the model.

  6. Execute an appropriate tool when requested.

  7. Return the model's response.

For the multiplication example, the expected result is 1,000.

If the agent cannot connect to the server, check that:

  • Python 3.11 or later is installed.

  • The MCP SDK is installed.

  • The OpenAI Agents SDK is installed.

  • The API key is configured correctly.

  • You are running the command from the project directory.

  • The server starts without Python errors.

If you modify the server's tools, restart the agent so that the new server definitions can be discovered.

10. Connecting to Other MCP Servers

One major advantage of MCP is that you are not limited to the server you created.

You can connect compatible MCP servers that expose other capabilities.

For example, an agent might use:

MCP Server /o:p

|

Possible Capabilities /o:p

|
|

Filesystem server /o:p

|

Read and manage permitted files/o:p

|
|

Database server /o:p

|

Retrieve and update database records/o:p

|
|

GitHub server /o:p

|

Access repositories and development information/o:p

|
|

Browser or search server /o:p

|

Retrieve information from permitted web sources/o:p

|
|

Calendar server /o:p

|

Read and manage calendar events/o:p

|

/o:pThese are examples of integrations, not tools automatically included in your project. Each server must be installed, configured, and authorized separately.

For instance, the official MCP Filesystem Server can be launched through a local subprocess connection. The OpenAI Agents SDK documentation provides examples using MCPServerStdio to connect to existing servers.

When connecting external servers, inspect their available tools before granting access.

Do not assume that a server is safe simply because it supports MCP. Check its source, permissions, authentication requirements, and actual implementation.

Also distinguish between local and remote connections.

stdio transport is useful for local servers that an application launches as subprocesses.

Streamable HTTP transport is useful when an MCP server is accessed through an HTTP endpoint. It is generally more suitable for network-based deployments.

The transport determines how the client communicates with the server. It does not change the basic purpose of the tools exposed by that server.

11. Taking Your MCP Agent Beyond the Beginner Project

Once your first agent is operational, you can extend it in several directions.

Add more Python tools.

You can register additional functions for calculations, data retrieval, document processing, and other tasks.

Each function should have a clear description, typed arguments, input validation, and appropriate permissions.

Introduce resources.

Resources allow your MCP server to expose information that an application can retrieve and supply to the model.

For example, you could expose documentation, configuration information, or approved project records.

Introduce reusable prompts.

MCP prompts allow you to provide predefined instructions for common activities.

A development assistant could expose prompts for code review, debugging, and technical documentation.

Connect databases.

You can create tools that interact with a database. However, database access should be restricted to approved operations.

For example, a reporting agent might retrieve sales records without receiving permission to delete or modify them.

Use Streamable HTTP for deployment.

When your application needs to connect to a server over a network, you can run the MCP server using Streamable HTTP.

The official Python SDK supports this transport and provides configuration options for hosting the server.

For remote deployments, authentication, authorization, network security, and access restrictions must be implemented appropriately.

Add monitoring and testing.

A production agent should have tests for its tools, error handling, permissions, and expected behavior.

You should also maintain records of important operations, particularly when the agent can modify external systems.

The objective is not simply to make the agent execute more tasks. It is to ensure that every available operation has a defined purpose and an appropriate level of access.

12. Conclusion

Building an AI agent with Model Context Protocol and Python provides a practical way to connect language models to external tools and services.

In this tutorial, you have covered the essential development process:

  • Prepared a Python development environment.

  • Installed the official MCP Python SDK.

  • Created an MCP server.

  • Registered Python functions as tools.

  • Tested the server using MCP Inspector.

  • Connected the server to an AI agent using the OpenAI Agents SDK.

  • Introduced approval controls for sensitive operations.

  • Created a restricted file-writing tool.

  • Explored ways to connect additional MCP servers.

The most important concept is the separation of responsibilities. The language model interprets requests and determines which available tools may help. The MCP client handles communication with the server. The server executes the registered functions, subject to the application's security controls.

This architecture provides a foundation for developing AI assistants that can interact with databases, files, APIs, and other external services.

Your first project is a starting point. You can extend it into a research assistant, document-processing application, coding assistant, or business automation system.

However, reliable agent development requires more than successful tool execution. Input validation, restricted permissions, human approval, error handling, and monitoring must remain part of the development process.

An AI agent should only have the access necessary to complete its assigned tasks. Its ability to execute an operation must never be confused with permission to execute that operation.

This article was originally published on The Worthy Son Media.

Top comments (0)