{ "cells": [ { "cell_type": "raw", "metadata": { "vscode": { "languageId": "raw" } }, "source": [ "# 🚀 Introduction to MCP (Model Control Protocol)\n", "\n", "Welcome to your journey into the world of **Model Control Protocol (MCP)**! This notebook will give you a comprehensive introduction to what MCP is, why it exists, and how it's revolutionizing the way AI assistants interact with the world.\n", "\n", "## 🎯 Learning Objectives\n", "\n", "By the end of this notebook, you will:\n", "- Understand what MCP is and why it's important\n", "- Know the key components of the MCP ecosystem\n", "- Learn about prompts, tools, and resources\n", "- Be prepared to build your first MCP server\n", "\n", "## 📚 Table of Contents\n", "\n", "1. [What is MCP?](#what-is-mcp)\n", "2. [Core Components](#core-components)\n", "3. [MCP Architecture](#mcp-architecture)\n", "4. [Building Blocks](#building-blocks)\n", "5. [Getting Started](#getting-started)\n", "\n", "---\n" ] }, { "cell_type": "raw", "metadata": { "vscode": { "languageId": "raw" } }, "source": [ "## 🤔 What is MCP?\n", "\n", "**Model Control Protocol (MCP)** is the official standard for enabling AI assistants to interact with external tools and services. It provides a secure, standardized way for language models to:\n", "\n", "- Execute functions and tools\n", "- Access structured data and resources\n", "- Handle system prompts and responses\n", "- Manage state and context\n", "\n", "### 🔑 Key Features\n", "\n", "- **FastMCP Framework**: Modern, async-first implementation\n", "- **Type Safety**: Built-in validation with Pydantic\n", "- **Prompts System**: Structured prompt management\n", "- **Resource Providers**: Unified data access layer\n", "- **Transport Layer**: HTTP, WebSocket, and Unix socket support\n", "\n", "### 🌟 Why MCP Matters\n", "\n", "The MCP ecosystem provides:\n", "- **Standardization**: One protocol for all AI integrations\n", "- **Type Safety**: Catch errors before runtime\n", "- **Modern Patterns**: Async/await, decorators, resources\n", "- **Security**: Built-in authentication and validation\n", "- **Scalability**: Production-ready architecture\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "ename": "", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31mRunning cells with 'Python 3.12.6' requires the ipykernel package.\n", "\u001b[1;31mRun the following command to install 'ipykernel' into the Python environment. \n", "\u001b[1;31mCommand: '/opt/homebrew/bin/python3 -m pip install ipykernel -U --user --force-reinstall'" ] } ], "source": [ "# Let's create a simple visualization to show the MCP ecosystem\n", "import matplotlib.pyplot as plt\n", "import matplotlib.patches as patches\n", "from matplotlib.patches import FancyBboxPatch\n", "import numpy as np\n", "\n", "fig, ax = plt.subplots(1, 1, figsize=(12, 8))\n", "\n", "# Define colors\n", "ai_color = '#4A90E2'\n", "mcp_color = '#50C878'\n", "tool_color = '#FF6B6B'\n", "\n", "# AI Assistant box\n", "ai_box = FancyBboxPatch((1, 6), 2.5, 1.5, boxstyle=\"round,pad=0.1\", \n", " facecolor=ai_color, edgecolor='black', linewidth=2)\n", "ax.add_patch(ai_box)\n", "ax.text(2.25, 6.75, 'AI Assistant\\n(Claude, GPT, etc.)', ha='center', va='center', \n", " fontsize=10, fontweight='bold', color='white')\n", "\n", "# MCP Protocol box (center)\n", "mcp_box = FancyBboxPatch((5, 4), 3, 4, boxstyle=\"round,pad=0.1\", \n", " facecolor=mcp_color, edgecolor='black', linewidth=2)\n", "ax.add_patch(mcp_box)\n", "ax.text(6.5, 6, 'MCP\\nProtocol', ha='center', va='center', \n", " fontsize=14, fontweight='bold', color='white')\n", "\n", "# Tool boxes\n", "tools = [\n", " ('Database\\nConnector', 10, 7),\n", " ('File System\\nManager', 10, 5.5),\n", " ('API\\nIntegrator', 10, 4),\n", " ('Web\\nScraper', 10, 2.5),\n", " ('Email\\nSender', 10, 1)\n", "]\n", "\n", "for tool_name, x, y in tools:\n", " tool_box = FancyBboxPatch((x, y), 2, 1, boxstyle=\"round,pad=0.1\", \n", " facecolor=tool_color, edgecolor='black', linewidth=1)\n", " ax.add_patch(tool_box)\n", " ax.text(x+1, y+0.5, tool_name, ha='center', va='center', \n", " fontsize=9, fontweight='bold', color='white')\n", "\n", "# Arrows from AI to MCP\n", "ax.annotate('', xy=(5, 6.5), xytext=(3.5, 6.75), \n", " arrowprops=dict(arrowstyle='->', lw=2, color='black'))\n", "ax.text(4.25, 7, 'Requests', ha='center', va='bottom', fontsize=9)\n", "\n", "# Arrows from MCP to Tools\n", "for _, x, y in tools:\n", " ax.annotate('', xy=(x, y+0.5), xytext=(8, 6), \n", " arrowprops=dict(arrowstyle='->', lw=1.5, color='black'))\n", "\n", "ax.set_xlim(0, 13)\n", "ax.set_ylim(0, 9)\n", "ax.set_aspect('equal')\n", "ax.axis('off')\n", "ax.set_title('MCP Ecosystem Architecture', fontsize=16, fontweight='bold', pad=20)\n", "\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "print(\"🎯 MCP acts as a centralized hub that connects AI assistants to various external tools and services!\")\n" ] }, { "cell_type": "raw", "metadata": { "vscode": { "languageId": "raw" } }, "source": [ "## 🧩 Core Components\n", "\n", "The MCP ecosystem consists of three main building blocks:\n", "\n", "### 1. **Prompts** 🗣️\n", "```python\n", "@mcp.prompt()\n", "def system_prompt() -> str:\n", " \"\"\"Define the AI assistant's role\"\"\"\n", " return \"\"\"You are an AI assistant...\"\"\"\n", "```\n", "\n", "### 2. **Tools** 🔧\n", "```python\n", "@mcp.tool()\n", "async def get_data(query: str) -> Dict:\n", " \"\"\"Fetch data based on query\"\"\"\n", " return {\"result\": \"data\"}\n", "```\n", "\n", "### 3. **Resources** 📦\n", "```python\n", "@mcp.resource(\"data://{id}\")\n", "async def get_resource(id: str) -> Any:\n", " \"\"\"Access structured data\"\"\"\n", " return load_data(id)\n", "```\n", "\n", "### 🏗️ FastMCP Architecture\n", "\n", "```python\n", "from mcp.server.fastmcp import FastMCP\n", "import mcp.types as types\n", "\n", "# Create MCP server\n", "mcp = FastMCP(\"my_server\")\n", "\n", "# Define components\n", "@mcp.prompt()\n", "def system_prompt() -> str:\n", " return \"System instructions...\"\n", "\n", "@mcp.tool()\n", "async def my_tool() -> Dict:\n", " return {\"status\": \"success\"}\n", "\n", "@mcp.resource(\"data://{key}\")\n", "async def my_resource(key: str) -> Any:\n", " return {\"key\": key}\n", "\n", "# Run server\n", "if __name__ == \"__main__\":\n", " mcp.run(transport=\"streamable-http\")\n", "```\n" ] }, { "cell_type": "raw", "metadata": { "vscode": { "languageId": "raw" } }, "source": [ "## 🎯 Common Use Cases\n", "\n", "MCP enables a wide variety of practical applications:\n", "\n", "### 📊 **Data Integration**\n", "- Connect AI to databases (PostgreSQL, MongoDB, etc.)\n", "- Access and analyze spreadsheets and CSV files\n", "- Query data warehouses and analytics platforms\n", "\n", "### 🌐 **API Integration**\n", "- Weather services and environmental data\n", "- Social media platforms and content APIs \n", "- Payment processing and e-commerce platforms\n", "- News feeds and content aggregation\n", "\n", "### 📁 **File Operations**\n", "- Read, write, and organize files and directories\n", "- Process documents (PDF, Word, Excel)\n", "- Image and video manipulation\n", "- Backup and synchronization\n", "\n", "### 🔐 **Secure Operations**\n", "- User authentication and authorization\n", "- Encrypted communication and data storage\n", "- Audit logging and compliance tracking\n", "\n", "### 🤖 **Automation** \n", "- Workflow orchestration and task scheduling\n", "- Email and notification systems\n", "- Report generation and distribution\n", "- System monitoring and alerting\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's see a simple example of what an MCP interaction might look like\n", "# This is just a conceptual example - we'll build real ones in later notebooks!\n", "\n", "print(\"🎭 Example MCP Interaction\")\n", "print(\"=\" * 50)\n", "print()\n", "\n", "# Simulate an AI assistant request\n", "print(\"🤖 AI Assistant:\")\n", "print(\" 'I need to check the weather in San Francisco and save the result to a file'\")\n", "print()\n", "\n", "# MCP coordinates the request\n", "print(\"🔄 MCP Protocol:\")\n", "print(\" 1. Routes weather request to Weather API Server\")\n", "print(\" 2. Authenticates with weather service\")\n", "print(\" 3. Retrieves current weather data\") \n", "print(\" 4. Routes file write request to File System Server\")\n", "print(\" 5. Saves weather data to specified file\")\n", "print()\n", "\n", "# Mock response\n", "weather_data = {\n", " \"location\": \"San Francisco, CA\",\n", " \"temperature\": \"68°F\",\n", " \"condition\": \"Partly Cloudy\",\n", " \"humidity\": \"65%\",\n", " \"wind\": \"8 mph NW\"\n", "}\n", "\n", "print(\"📊 Weather API Server Response:\")\n", "for key, value in weather_data.items():\n", " print(f\" {key.title()}: {value}\")\n", "print()\n", "\n", "print(\"💾 File System Server:\")\n", "print(\" ✅ Weather data saved to 'sf_weather.json'\")\n", "print()\n", "\n", "print(\"🎯 Result: The AI assistant successfully retrieved weather data\")\n", "print(\" and saved it to a file using two different MCP servers!\")\n", "print()\n", "print(\"🚀 This is the power of MCP - seamless integration with multiple services!\")\n" ] }, { "cell_type": "raw", "metadata": { "vscode": { "languageId": "raw" } }, "source": [ "## 🎓 What You've Learned\n", "\n", "✅ **MCP Core Concepts**: Protocol fundamentals and architecture\n", "✅ **Building Blocks**: Prompts, Tools, and Resources\n", "✅ **Modern Patterns**: FastMCP and type-safe development\n", "✅ **Best Practices**: Official implementation patterns\n", "\n", "## 🚀 Next Steps\n", "\n", "Continue your MCP journey:\n", "\n", "1. [Environment Setup](02_environment_setup.ipynb)\n", "2. [Your First MCP Server](03_your_first_mcp.ipynb)\n", "3. [Working with Tools](04_basic_tools.ipynb)\n", "4. [Advanced Patterns](05_protocol_deep_dive.ipynb)\n", "\n", "## 💡 Pro Tips\n", "\n", "- Use type hints for better IDE support\n", "- Leverage async/await for performance\n", "- Structure your code with FastMCP patterns\n", "- Follow the official MCP specification\n", "\n", "---\n", "\n", "Ready to build your first MCP server? Let's go to [Environment Setup](02_environment_setup.ipynb)!\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.12.6" } }, "nbformat": 4, "nbformat_minor": 2 }