genai · temario
4.23tema 23 de 30

MCP — construir server y client

Exponer tools/resources y conectar hosts a tus datos

Construir un MCP server con el SDK de Python es directo: instanciar `FastMCP`, decorar funciones con `@mcp.tool()` o `@mcp.resource()`, y arrancarlo. El SDK maneja el handshake de inicialización, la serialización JSON-RPC, el listado de capacidades y el routing de llamadas. Tu trabajo es escribir las funciones de negocio y sus schemas — el protocolo queda oculto.

Exponer **tools** significa definir funciones que el LLM puede invocar con argumentos. El SDK genera automáticamente el `inputSchema` a partir de los type hints y las docstrings de Python. Una buena tool tiene: nombre en snake_case que describe la acción, docstring de una línea con qué hace, parámetros tipados con Pydantic cuando la validación importa, y un retorno serializable (dict, list, str). El LLM decide cuándo llamar la tool basándose en la descripción — si es vaga, la invocará mal.

Exponer **resources** es diferente: en lugar de que el LLM los invoque, el host los pone disponibles en el contexto. Un resource tiene una URI (`file://`, `db-schema://`, un esquema personalizado), un nombre legible y un mime type. Se usan para datos relativamente estáticos que el LLM debe poder consultar como referencia: el schema de una base de datos, la documentación de una API, el contenido de un directorio.

En la parte del **client**, conectarse a un server MCP requiere crear un `ClientSession`, establecer el transporte (stdio o SSE), llamar a `initialize()` y luego descubrir las capacidades con `list_tools()` / `list_resources()`. La mayoría de los hosts (Claude Desktop, Cursor, LangChain) hacen esto automáticamente — pero si construyes tu propio host o quieres testear el server directamente, necesitas saber cómo funciona el client.

La diferencia entre **conexión local y remota** determina el transporte. Local significa que el host lanza el server como subproceso (stdio): startup en milisegundos, sin red, sin autenticación. Remoto significa que el server ya está corriendo en algún lugar con un puerto HTTP: múltiples hosts pueden conectarse, pero hay latencia de red y debes gestionar autenticación (OAuth, API keys en headers). El SDK soporta ambos modos con configuración mínima.

El **testing** del server es el paso que más se omite. La forma correcta: primero unitario (testear la función de negocio pura sin MCP), luego de integración (usar el client del SDK para llamar al server en proceso y verificar que el JSON-RPC es correcto), y finalmente con el MCP Inspector (`npx @modelcontextprotocol/inspector`) para explorar tools y resources desde una UI. No esperes al host final para descubrir que un tool retorna un tipo no serializable.

structure.txt
# Building an MCP server with the Python SDK

# pip install 'mcp[cli]'

from mcp.server.fastmcp import FastMCP
import httpx

mcp = FastMCP('weather-server')

# === TOOL: callable by the LLM ===
@mcp.tool()
def get_weather(city: str, units: str = 'metric') -> dict:
    '''Get current weather for a city. Units: metric (°C) or imperial (°F).'''
    response = httpx.get(
        'https://api.openweathermap.org/data/2.5/weather',
        params={'q': city, 'units': units, 'appid': OPENWEATHER_KEY},
    )
    response.raise_for_status()
    data = response.json()
    return {
        'city': data['name'],
        'temp': data['main']['temp'],
        'description': data['weather'][0]['description'],
    }

# === RESOURCE: context data pulled by the host ===
@mcp.resource('config://supported-cities')
def list_supported_cities() -> str:
    '''List of cities covered by this weather server.'''
    return 'Buenos Aires, Lima, Madrid, Mexico City, Bogota'

# Run with stdio (local) transport
if __name__ == '__main__':
    mcp.run(transport='stdio')

# Run with HTTP+SSE (remote) transport:
# mcp.run(transport='sse', port=8080)


# === CLIENT: connecting to the server programmatically ===

# pip install 'mcp[cli]'

import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def run_client():
    server_params = StdioServerParameters(
        command='python',
        args=['weather_server.py'],
    )
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # Discover capabilities
            tools = await session.list_tools()
            print('Available tools:', [t.name for t in tools.tools])

            # Call a tool directly
            result = await session.call_tool(
                'get_weather',
                arguments={'city': 'Lima', 'units': 'metric'},
            )
            print(result.content[0].text)

asyncio.run(run_client())


# === Claude Desktop config (stdio, local) ===
# ~/Library/Application Support/Claude/claude_desktop_config.json
# {
#   "mcpServers": {
#     "weather": {
#       "command": "python",
#       "args": ["/absolute/path/to/weather_server.py"],
#       "env": { "OPENWEATHER_KEY": "..." }
#     }
#   }
# }

Katas (7)

Debugging lab

Detecta y corrige el error en el código.

0/6 tests passing0%
  1. 4.23.5.1

    from mcp.server.fastmcp import FastMCP mcp = FastMCP('my-server') @mcp.tool() def search(q): return db.search(q) # no type hints, no docstring

  2. 4.23.5.2

    # Client connects without initializing async with ClientSession(read, write) as session: tools = await session.list_tools() # called before initialize()

  3. 4.23.5.3

    @mcp.tool() def get_user_profile(user_id: str) -> dict: '''Get user profile.''' conn = psycopg2.connect(host='localhost', user='admin', password='s3cr3t') # hardcoded credentials return db_query(conn, user_id)

  4. 4.23.5.4

    # Dynamic data exposed as a resource @mcp.resource('db://users/{user_id}') def get_user(user_id: str) -> str: return json.dumps(db.get_user(user_id)) # changes on every call, requires arguments

  5. 4.23.5.5

    # Tool returns a non-serializable object from datetime import datetime @mcp.tool() def get_timestamps() -> list: '''Return recent event timestamps.''' return [datetime(2025, 1, 1), datetime(2025, 6, 15)] # datetime objects

  6. 4.23.5.6

    # Claude Desktop config with relative path { "mcpServers": { "myserver": { "command": "python", "args": ["./server.py"] # relative path } } }