MCPLEARNING
MCP + LangChain Demo
Un proyecto para principiantes que demuestra cómo construir servidores MCP (Model Context Protocol) y conectarlos a un agente LLM usando LangChain y LangGraph.
¿Qué es MCP?
MCP (Model Context Protocol) es un protocolo abierto que te permite exponer herramientas personalizadas (funciones) a los LLM de manera estandarizada. Piensa en él como un sistema de plugins universal para modelos de IA.
Conceptos clave:
Término | Definición |
Servidor MCP | Un proceso que expone herramientas a través de un transporte (stdio o HTTP). El LLM puede llamar a estas herramientas. |
Cliente MCP | Un proceso que se conecta a uno o más servidores MCP, descubre sus herramientas y las reenvía a un LLM. |
Herramienta | Una función de Python decorada con |
Transporte | El método de comunicación entre cliente y servidor. |
FastMCP | Una clase de Python de alto nivel de la librería |
Related MCP server: Model Context Protocol Multi-Agent Server
Estructura del Proyecto
MCPLEARNING/
├── mathserver.py # MCP Server 1 - Math tools (stdio transport)
├── weather.py # MCP Server 2 - Weather tool (HTTP transport)
├── client.py # LangChain agent that connects to both servers
├── .env # API keys (NOT pushed to GitHub)
├── .gitignore
├── requirements.txt
└── pyproject.tomlCómo Funciona (Paso a Paso)
Paso 1: Servidor MCP — mathserver.py
Este archivo crea un servidor MCP llamado "Math" que expone dos herramientas:
add(a, b)— Devuelve la suma de dos enteros.multiply(a, b)— Devuelve el producto de dos enteros.
Se ejecuta en transporte stdio, lo que significa que el cliente lo inicia como un subproceso y se comunica a través de stdin/stdout. No se necesita puerto.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Math")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Addition of two numbers"""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiplication of two numbers"""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")Paso 2: Servidor MCP — weather.py
Este archivo crea un servidor MCP llamado "Weather" que expone una herramienta:
get_weather(location)— Devuelve información meteorológica para una ubicación dada.
Se ejecuta en transporte streamable-http, lo que significa que inicia un servidor web en http://127.0.0.1:8000/mcp. El cliente se conecta a él a través de HTTP.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather")
@mcp.tool()
async def get_weather(location: str) -> str:
"""Get the weather"""
return "It's always raining in California"
if __name__ == "__main__":
mcp.run(transport="streamable-http")Paso 3: Agente Cliente — client.py
Este es el cerebro del proyecto. Hace lo siguiente:
Se conecta a ambos servidores MCP usando
MultiServerMCPClient.Descubre todas las herramientas de ambos servidores (
add,multiply,get_weather).Crea un LLM de Groq (modelo open-source alojado) y vincula las herramientas a él.
Construye un agente de LangGraph — una máquina de estados donde:
El LLM decide si llamar a una herramienta o responder directamente.
Si se llama a una herramienta, el resultado se devuelve al LLM para una respuesta final.
Prueba dos consultas:
"¿Cuánto es 3 + 5?" → Usa la herramienta
add."¿Cuál es el clima en California?" → Usa la herramienta
get_weather.
Requisitos Previos
Python 3.13+
Gestor de paquetes uv (recomendado) o pip
Una clave API de Groq — Obtén una gratis en console.groq.com
Configuración
1. Clonar el repositorio
git clone https://github.com/<YOUR_USERNAME>/MCPLEARNING.git
cd MCPLEARNING2. Crear y activar el entorno virtual
# Using uv (recommended)
uv venv
uv pip install -r requirements.txt
# Or using pip
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # Mac/Linux
pip install -r requirements.txt3. Configurar tu clave API
Crea un archivo .env en la raíz del proyecto:
GROQ_API_KEY=your_groq_api_key_hereIMPORTANTE: Nunca subas tu archivo
.env. Está excluido mediante.gitignore.
Ejecutar el Proyecto
Necesitas dos terminales abiertas:
Terminal 1 — Iniciar el Servidor MCP de Clima
python weather.pyDeberías ver:
INFO: Uvicorn running on http://127.0.0.1:8000Nota: Solo
weather.pydebe iniciarse manualmente.mathserver.pyse inicia automáticamente desde el cliente (transporte stdio).
Terminal 2 — Ejecutar el Cliente
python client.pySalida Esperada
Available MCP tools:
- add
- multiply
- get_weather
==============================
Testing Math MCP
==============================
Math Response: 3 + 5 = 8.
==============================
Testing Weather MCP
==============================
Weather Response: It's always raining in California.Cómo Crear Tu Propio Servidor MCP
Instala la librería MCP:
pip install mcpCrea un nuevo archivo Python (ej.,
myserver.py):
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("MyServer")
@mcp.tool()
def my_tool(param: str) -> str:
"""Description of what this tool does."""
return f"Result: {param}"
if __name__ == "__main__":
mcp.run(transport="stdio") # For stdio transport
# mcp.run(transport="streamable-http") # For HTTP transportConéctalo en tu cliente añadiéndolo a la configuración de
MultiServerMCPClient:
client = MultiServerMCPClient({
"myserver": {
"command": "python",
"args": ["myserver.py"],
"transport": "stdio",
},
})Comparación de Transportes
Transporte | Cómo funciona | Cuándo usarlo |
stdio | El cliente inicia el servidor como un subproceso. Se comunica vía stdin/stdout. | Herramientas locales, configuración simple, sin necesidad de red. |
streamable-http | El servidor se ejecuta como un servidor web. El cliente se conecta vía HTTP. | Herramientas remotas, múltiples clientes, acceso entre máquinas. |
Librerías Clave Utilizadas
Librería | Propósito |
| Construir servidores MCP con |
| Puente entre servidores MCP y herramientas de LangChain. |
| Integración de LangChain para LLM alojados en Groq. |
| Construir flujos de trabajo de agente como un grafo (bucle agente ↔ herramientas). |
| Cargar claves API desde archivo |
Cosas Importantes a Tener en Cuenta
El servidor de clima debe estar ejecutándose antes que el cliente — Como usa transporte HTTP, el proceso del servidor debe iniciarse primero. El servidor de matemáticas (stdio) se inicia automáticamente desde el cliente.
Se requiere la clave API de Groq — Sin ella, las llamadas al LLM fallarán. Obtén una clave gratuita en console.groq.com.
Nunca subir
.env— Siempre añade.enva.gitignoreantes de subir código.Conflictos de puerto — El servidor de clima se ejecuta en el puerto 8000 por defecto. Si otro proceso usa ese puerto, el servidor no se iniciará.
Problema de codificación en Windows — En Windows, la consola puede no admitir caracteres UTF-8 devueltos por el LLM.
client.pymaneja esto consys.stdout.reconfigure(encoding="utf-8").Disponibilidad del modelo — El nombre del modelo de Groq (
openai/gpt-oss-120b) debe ser válido y estar disponible en la plataforma Groq. Consulta la lista de modelos de Groq para conocer las opciones actuales.
This server cannot be installed
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- Flicense-qualityDmaintenanceA Model Context Protocol (MCP) server that demonstrates mathematical capabilities through a LangChain integration, allowing clients to perform math operations via the MCP protocol.
- Flicense-qualityDmaintenanceDemonstrates custom MCP servers for math and weather operations, enabling multi-agent orchestration using LangChain, Groq, and MCP adapters for both local and remote tool integration.1
- Flicense-qualityCmaintenanceA demonstration MCP server that provides math (add/multiply) and weather tools, connecting via stdio and streamable HTTP, and integrates with LangChain and LangGraph for agentic workflows.
- Flicense-qualityDmaintenanceA collection of MCP servers demonstrating math operations, weather data, and LangGraph workflows.1
Related MCP Connectors
MCP server for AI dialogue using various LLM models via AceDataCloud
MCP server exposing the Backtest360 engine API as tools for AI agents.
MCP server for AI agents to plan, verify, and deploy Cloudflare-native apps.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Reyansh1996/MCPLEARNING'
If you have feedback or need assistance with the MCP directory API, please join our Discord server