Files
2025-09-11 23:22:04 +01:00

7.8 KiB

Model Context Protocol (MCP) Developer Guide

What is MCP?

MCP (Model Context Protocol) is an open-source standard for connecting AI applications to external systems. Using MCP, AI applications like Claude or ChatGPT can connect to data sources (local files, databases), tools (search engines, calculators), and workflows (specialized prompts)—enabling them to access key information and perform tasks.

Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect electronic devices, MCP provides a standardized way to connect AI applications to external systems.

MCP Overview

MCP Introduction

The diagram above illustrates how MCP creates a standardized interface between AI models and external tools/data sources through MCP servers that act as intermediaries.

Core MCP Concepts

MCP servers can provide three main types of capabilities that enable AI applications to interact with external systems:

🔧 Tools

Functions that can be called by the LLM (with user approval)

Tools are the primary way AI models perform actions and computations. They represent executable functions that the AI can invoke to:

  • Perform calculations (like our calculator example)
  • Execute system commands
  • Query databases
  • Interact with APIs
  • Process data

Example Implementation:

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers together"""
    return a + b

Key Characteristics:

  • Require explicit user approval before execution
  • Can have complex input/output schemas
  • Enable AI to perform real-world actions
  • Primary focus of this tutorial

📄 Resources

File-like data that can be read by clients

Resources represent data sources that AI can access and read, similar to files or API responses:

  • File contents (local or remote files)
  • Database records
  • API responses
  • Configuration data
  • Log files

Example Use Cases:

  • Reading documentation files
  • Accessing configuration settings
  • Querying data from databases
  • Retrieving API responses

📝 Prompts

Pre-written templates that help users accomplish specific tasks

Prompts are reusable templates that guide AI behavior for specific scenarios:

  • Task-specific instructions
  • Workflow templates
  • Specialized conversation starters
  • Domain-specific guidance

Example Applications:

  • Code review templates
  • Customer service response formats
  • Technical writing guidelines
  • Analysis frameworks

Transport Protocols

MCP supports multiple transport protocols for communication between clients and servers:

1. Server-Sent Events (SSE)

  • Use Case: Web-based applications, remote connections
  • Communication: HTTP-based, unidirectional from server to client
  • Implementation: Uses HTTP endpoints for real-time communication
  • Port: Configurable (default: 8050)

2. Standard Input/Output (STDIO)

  • Use Case: Local applications, direct process communication
  • Communication: Direct process pipes, bidirectional
  • Implementation: Launches server as subprocess with stdin/stdout pipes
  • Setup: No network configuration required

Setup Mechanism

The setup mechanism diagram shows how different transport protocols handle the connection establishment between MCP clients and servers.

Project Structure

This repository contains example implementations demonstrating MCP concepts:

intro_test/ - Basic MCP Implementation

This folder provides fundamental MCP server and client examples:

  • server.py - MCP server with calculator tool using FastMCP
  • client_sse.py - Client connecting via SSE transport
  • client_stdio.py - Client connecting via STDIO transport
  • main.py - Main entry point for testing
  • Config.py - Configuration management

Key Features:

  • Simple calculator tool (add function)
  • Support for both SSE and STDIO transports
  • Environment variable configuration
  • FastMCP framework usage

intro_test/openai_test/ - OpenAI Integration

This folder demonstrates MCP integration with OpenAI:

  • client.py - MCP-OpenAI client class with tool calling
  • server.py - MCP server for the integration example
  • data/kb.json - Knowledge base data for AI responses

Key Features:

  • Seamless OpenAI API integration
  • Automatic tool discovery and execution
  • Conversation management with tool results
  • Error handling and cleanup
  • Knowledge base tool with JSON data integration

Quick Start

Prerequisites

  • Python 3.13+
  • OpenAI API key (for OpenAI integration examples)

Installation

# Clone the repository
git clone <repository-url>
cd mcp_template

# Navigate to intro_test directory
cd intro_test

# Install dependencies using uv (recommended)
uv sync

# Or using pip (if you prefer)
pip install -e .

Environment Setup

Create a .env file in the project root:

# Create .env file
touch .env

Then add your OpenAI API key to the .env file:

OPENAI_API_KEY=your_openai_api_key_here

Note: Get your API key from OpenAI Platform

Running Basic Examples

  1. Start the MCP Server (SSE Transport):
cd intro_test
uv run server.py
  1. Run the SSE Client:
uv run client_sse.py
  1. Run the STDIO Client:
uv run client_stdio.py

OpenAI Integration Example

  1. Start the MCP Server:
cd intro_test
uv run python openai_test/server.py
  1. Run the OpenAI Client:
cd intro_test
uv run python openai_test/client.py

Note: The OpenAI integration examples must be run from the intro_test directory due to relative import dependencies.

Understanding the Code

Server Implementation

The server uses FastMCP framework to create MCP-compatible servers:

from mcp.server.fastmcp import FastMCP

mcp = FastMCP(
    name="Calculator",
    host="0.0.0.0",
    port=8050,
    stateless_http=True,
)

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers together"""
    return a + b

# Run with different transports
mcp.run(transport="sse")  # or "stdio" or "streamable-http"

Client Implementation

Clients connect to servers using different transport methods:

SSE Client:

async with sse_client("http://localhost:8050/sse") as (read_stream, write_stream):
    async with ClientSession(read_stream, write_stream) as session:
        await session.initialize()
        # Use tools...

STDIO Client:

server_params = StdioServerParameters(
    command="python",
    args=["server.py"],
)
async with stdio_client(server_params) as (read_stream, write_stream):
    async with ClientSession(read_stream, write_stream) as session:
        # Use tools...

OpenAI Integration

The OpenAI client bridges MCP tools with OpenAI's function calling:

# Get MCP tools in OpenAI format
tools = await self.get_mcp_tools()

# Make OpenAI API call with tools
response = await self.openai_client.chat.completions.create(
    model=self.model,
    messages=[{"role": "user", "content": query}],
    tools=tools,
    tool_choice="auto",
)

Next Steps

This guide covers the fundamentals of MCP development. The examples in this repository demonstrate:

  • Basic server and client setup
  • Multiple transport protocol implementations
  • OpenAI integration patterns
  • Tool definition and execution
  • Error handling and cleanup

Future enhancements may include:

  • Additional transport protocols
  • Advanced tool implementations
  • Database integrations
  • Webhook support
  • Authentication mechanisms

This documentation will be updated as new features and examples are added to the repository.

URL: https://modelcontextprotocol.io/docs/learn/architecture