Aquí se explica cómo ejecutar el servidor y cliente de streaming HTTP clásico, así como el servidor y cliente de streaming MCP usando Python.
- Configurarás un servidor MCP que transmite notificaciones de progreso al cliente mientras procesa elementos.
- El cliente mostrará cada notificación en tiempo real.
- Esta guía cubre los requisitos previos, la configuración, la ejecución y la solución de problemas.
- Python 3.9 o superior
- El paquete de Python
mcp(instalar conpip install mcp)
-
Clona el repositorio o descarga los archivos de la solución.
git clone https://github.com/microsoft/mcp-for-beginners
-
Crea y activa un entorno virtual (recomendado):
python -m venv venv .\venv\Scripts\Activate.ps1 # On Windows # or source venv/bin/activate # On Linux/macOS
-
Instala las dependencias necesarias:
pip install "mcp[cli]"
-
Navega al directorio de la solución:
cd 03-GettingStarted/06-http-streaming/solution
-
Inicia el servidor de streaming HTTP clásico:
python server.py
-
El servidor se iniciará y mostrará:
Starting FastAPI server for classic HTTP streaming... INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
-
Abre una nueva terminal (activa el mismo entorno virtual y directorio):
cd 03-GettingStarted/06-http-streaming/solution python client.py
-
Deberías ver los mensajes transmitidos impresos de forma secuencial:
Running classic HTTP streaming client... Connecting to http://localhost:8000/stream with message: hello --- Streaming Progress --- Processing file 1/3... Processing file 2/3... Processing file 3/3... Here's the file content: hello --- Stream Ended ---
- Navega al directorio de la solución:
cd 03-GettingStarted/06-http-streaming/solution
- Inicia el servidor MCP con el transporte streamable-http:
python server.py mcp
- El servidor se iniciará y mostrará:
Starting MCP server with streamable-http transport... INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
- Abre una nueva terminal (activa el mismo entorno virtual y directorio):
cd 03-GettingStarted/06-http-streaming/solution python client.py mcp
- Deberías ver las notificaciones impresas en tiempo real mientras el servidor procesa cada elemento:
Running MCP client... Starting client... Session ID before init: None Session ID after init: a30ab7fca9c84f5fa8f5c54fe56c9612 Session initialized, ready to call tools. Received message: root=LoggingMessageNotification(...) NOTIFICATION: root=LoggingMessageNotification(...) ... Tool result: meta=None content=[TextContent(type='text', text='Processed files: file_1.txt, file_2.txt, file_3.txt | Message: hello from client')]
- Crea el servidor MCP usando FastMCP.
- Define una herramienta que procese una lista y envíe notificaciones usando
ctx.info()orctx.log(). - Run the server with
transport="streamable-http". - Implement a client with a message handler to display notifications as they arrive.
- The server uses async functions and the MCP context to send progress updates.
- The client implements an async message handler to print notifications and the final result.
- Use
async/awaitpara operaciones no bloqueantes.** - Siempre maneja las excepciones tanto en el servidor como en el cliente para mayor robustez.
- Prueba con múltiples clientes para observar las actualizaciones en tiempo real.
- Si encuentras errores, verifica tu versión de Python y asegúrate de que todas las dependencias estén instaladas.
Aviso legal:
Este documento ha sido traducido utilizando el servicio de traducción automática Co-op Translator. Aunque nos esforzamos por la precisión, tenga en cuenta que las traducciones automáticas pueden contener errores o inexactitudes. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda la traducción profesional realizada por humanos. No nos hacemos responsables por malentendidos o interpretaciones erróneas que puedan derivarse del uso de esta traducción.