¡Hola developer 👋🏻! Ya estoy de vuelta de las vacaciones y vengo con las pilas cargadísimas 🔋 porque hoy te traigo un reto digno de jefe final 🧟♂️: montar un MCP Server con transporte Streameable HTTP (sí, el que está de moda para servidores remotos 😎), pero… ¡usando un Low-Level server! 🧠
¿Y eso qué significa exactamente? Probablemente ya tengas claro lo de MCP y el transporte, pero… ¿por qué meterse en las entrañas del servidor a tan bajo nivel? ¿En qué casos lo puedo necesitar? 🤔 Pues vamos a verlo 🤓
Cómo creamos normalmente los MCP Servers
Si quieres saber más sobre MCP Servers puedes echar un vistazo a mi primer vídeo donde además uso GitHub Copilot como cliente:
Cada vez que has creado un MCP Server, en este caso tomo como ejemplo TypeScript, lo más probable es que lo hayas hecho usando la clase McpServer de una forma parecida a esta:
const server = new McpServer({
name: "remote-mcp-server",
version: "1.0.0"
});Lo que realmente estamos haciendo es usar un wrapper que es mucho más intuitivo y sencillo que usar que la clase que realmente utiliza este por debajo, que se llama directamente Server (y es lo que en la documentación se define como Low-Level Server) que lo que nos va a dar es más funcionalidad y flexibilidad a la hora de configurar el servidor, pero que por otro lado va a ser un poquito más tedioso 🙃 ¿Y por qué me he metido en este jardín? pues en mi caso porque quería probar Sampling y a día de hoy con el wrapper parece ser que no está expuesta la llamada que debemos realizar y te tienes que ir a bajo nivel para conseguirlo… pero esa es otra historia para otro artículo… o vídeo 🤓 Pero también es útil cuando quieres enviar notificaciones, cuando quieres desarrollar un nuevo transporte, cuando quieres optimizar el rendimiento 🤯 Pero por ahora solo lo necesito para el Sampling 🥺
Nota 10/07/2025: Encontré otra forma de poder hacer sampling sin meterme este jardín usando el wrapper 😇
Ok, cómo crear un MCP Low-Level Server en TypeScript
Pues la forma más sencilla que he encontrado es haciendo uso de este comando de aquí:
npx @modelcontextprotocol/create-server mcp-low-level-server-streamable-httpNota: El segundo parámetro es el nombre extra largo que le he puesto para este repo, por lo que deberías cambiarlo al que se ajuste a tu servidor.
Sin embargo, tienes que tener en cuenta que esta plantilla está totalmente desactualizada y cuando crea tu proyecto está usando la versión 0.6.0 del SDK de MCP 😱
{
"name": "mcp-low-level-server-streamable-http",
"version": "0.1.0",
"description": "A Model Context Protocol server",
"private": true,
"type": "module",
"bin": {
"mcp-low-level-server-streamable-http": "./build/index.js"
},
"files": [
"build"
],
"scripts": {
"build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
"prepare": "npm run build",
"watch": "tsc --watch",
"inspector": "npx @modelcontextprotocol/inspector build/index.js"
},
"dependencies": {
"@modelcontextprotocol/sdk": "0.6.0"
},
"devDependencies": {
"@types/node": "^20.11.24",
"typescript": "^5.3.3"
}
}
por lo que, lo primero que debes hacer es actualizar las dependencias 📦
Por otro lado, lo segundo que te darás cuenta rápidamente es que esta plantilla de ejemplo utiliza STDIO como método de transporte, que no es justamente lo que necesito para mi caso en concreto donde voy a querer utilizar esas funcionalidades que a día de hoy solo están a bajo nivel en un servidor remoto. Así que aquí te dejo cómo era el código original:
#!/usr/bin/env node
/**
* This is a template MCP server that implements a simple notes system.
* It demonstrates core MCP concepts like resources and tools by allowing:
* - Listing notes as resources
* - Reading individual notes
* - Creating new notes via a tool
* - Summarizing all notes via a prompt
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
ListPromptsRequestSchema,
GetPromptRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
/**
* Type alias for a note object.
*/
type Note = { title: string, content: string };
/**
* Simple in-memory storage for notes.
* In a real implementation, this would likely be backed by a database.
*/
const notes: { [id: string]: Note } = {
"1": { title: "First Note", content: "This is note 1" },
"2": { title: "Second Note", content: "This is note 2" }
};
/**
* Create an MCP server with capabilities for resources (to list/read notes),
* tools (to create new notes), and prompts (to summarize notes).
*/
const server = new Server(
{
name: "mcp-low-level-server-streamable-http",
version: "0.1.0",
},
{
capabilities: {
resources: {},
tools: {},
prompts: {},
},
}
);
/**
* Handler for listing available notes as resources.
* Each note is exposed as a resource with:
* - A note:// URI scheme
* - Plain text MIME type
* - Human readable name and description (now including the note title)
*/
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: Object.entries(notes).map(([id, note]) => ({
uri: `note:///${id}`,
mimeType: "text/plain",
name: note.title,
description: `A text note: ${note.title}`
}))
};
});
/**
* Handler for reading the contents of a specific note.
* Takes a note:// URI and returns the note content as plain text.
*/
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const url = new URL(request.params.uri);
const id = url.pathname.replace(/^\//, '');
const note = notes[id];
if (!note) {
throw new Error(`Note ${id} not found`);
}
return {
contents: [{
uri: request.params.uri,
mimeType: "text/plain",
text: note.content
}]
};
});
/**
* Handler that lists available tools.
* Exposes a single "create_note" tool that lets clients create new notes.
*/
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "create_note",
description: "Create a new note",
inputSchema: {
type: "object",
properties: {
title: {
type: "string",
description: "Title of the note"
},
content: {
type: "string",
description: "Text content of the note"
}
},
required: ["title", "content"]
}
}
]
};
});
/**
* Handler for the create_note tool.
* Creates a new note with the provided title and content, and returns success message.
*/
server.setRequestHandler(CallToolRequestSchema, async (request) => {
switch (request.params.name) {
case "create_note": {
const title = String(request.params.arguments?.title);
const content = String(request.params.arguments?.content);
if (!title || !content) {
throw new Error("Title and content are required");
}
const id = String(Object.keys(notes).length + 1);
notes[id] = { title, content };
return {
content: [{
type: "text",
text: `Created note ${id}: ${title}`
}]
};
}
default:
throw new Error("Unknown tool");
}
});
/**
* Handler that lists available prompts.
* Exposes a single "summarize_notes" prompt that summarizes all notes.
*/
server.setRequestHandler(ListPromptsRequestSchema, async () => {
return {
prompts: [
{
name: "summarize_notes",
description: "Summarize all notes",
}
]
};
});
/**
* Handler for the summarize_notes prompt.
* Returns a prompt that requests summarization of all notes, with the notes' contents embedded as resources.
*/
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
if (request.params.name !== "summarize_notes") {
throw new Error("Unknown prompt");
}
const embeddedNotes = Object.entries(notes).map(([id, note]) => ({
type: "resource" as const,
resource: {
uri: `note:///${id}`,
mimeType: "text/plain",
text: note.content
}
}));
return {
messages: [
{
role: "user",
content: {
type: "text",
text: "Please summarize the following notes:"
}
},
...embeddedNotes.map(note => ({
role: "user" as const,
content: note
})),
{
role: "user",
content: {
type: "text",
text: "Provide a concise summary of all the notes above."
}
}
]
};
});
/**
* Start the server using stdio transport.
* This allows the server to communicate via standard input/output streams.
*/
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main().catch((error) => {
console.error("Server error:", error);
process.exit(1);
});
y en lo que lo he convertido para que el mismo ejemplo ahora funcione con Streamable HTTP:
/**
* 📝 MCP (Model Context Protocol) Sample Server
*
* Este archivo implementa un servidor didáctico usando el Model Context Protocol (MCP)
* para gestionar notas de texto. Utiliza la Low-Level API del SDK MCP y Express.js
* para exponer endpoints HTTP que permiten listar, leer, crear y resumir notas.
*
* Características principales:
* - Almacenamiento en memoria de notas (sin base de datos).
* - Exposición de recursos (notas) vía MCP.
* - Herramienta para crear nuevas notas.
* - Prompt para resumir todas las notas.
* - Manejo de sesiones MCP vía HTTP (POST, GET, DELETE).
*
* Ideal para aprender cómo funciona MCP y cómo integrar recursos, herramientas y prompts.
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
ListPromptsRequestSchema,
GetPromptRequestSchema,
isInitializeRequest,
} from "@modelcontextprotocol/sdk/types.js";
import { randomUUID } from "node:crypto";
import express, { Request, Response } from "express";
/**
* Tipo para una nota.
*/
type Note = { title: string; content: string };
/**
* Almacenamiento en memoria de notas.
* En una app real, esto sería una base de datos.
*/
const notes: { [id: string]: Note } = {
"1": { title: "First Note", content: "This is note 1" },
"2": { title: "Second Note", content: "This is note 2" },
};
// 🚀 Inicializa la app Express
const app = express();
app.use(express.json());
// Mapa de transports por sesión
const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
// 🛠️ Crea el servidor MCP con capacidades de recursos, herramientas y prompts
const server = new Server(
{
name: "mcp-sampling",
version: "0.1.0",
},
{
capabilities: {
resources: {},
tools: {},
prompts: {},
// sampling: {}
},
}
);
/**
* 📋 Handler para listar notas como recursos MCP.
*/
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: Object.entries(notes).map(([id, note]) => ({
uri: `note:///${id}`,
mimeType: "text/plain",
name: note.title,
description: `A text note: ${note.title}`,
})),
};
});
/**
* 📖 Handler para leer el contenido de una nota.
*/
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const url = new URL(request.params.uri);
const id = url.pathname.replace(/^\//, "");
const note = notes[id];
if (!note) {
throw new Error(`Note ${id} not found`);
}
return {
contents: [
{
uri: request.params.uri,
mimeType: "text/plain",
text: note.content,
},
],
};
});
/**
* 🛠️ Handler para listar herramientas disponibles (solo "create_note").
*/
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "create_note",
description: "Create a new note",
inputSchema: {
type: "object",
properties: {
title: {
type: "string",
description: "Title of the note",
},
content: {
type: "string",
description: "Text content of the note",
},
},
required: ["title", "content"],
},
},
],
};
});
/**
* 📝 Handler para la herramienta "create_note".
*/
server.setRequestHandler(CallToolRequestSchema, async (request) => {
switch (request.params.name) {
case "create_note": {
const title = String(request.params.arguments?.title);
const content = String(request.params.arguments?.content);
if (!title || !content) {
throw new Error("Title and content are required");
}
const id = String(Object.keys(notes).length + 1);
notes[id] = { title, content };
return {
content: [
{
type: "text",
text: `Created note ${id}: ${title}`,
},
],
};
}
default:
throw new Error("Unknown tool");
}
});
/**
* 💡 Handler para listar prompts disponibles (solo "summarize_notes").
*/
server.setRequestHandler(ListPromptsRequestSchema, async () => {
return {
prompts: [
{
name: "summarize_notes",
description: "Summarize all notes",
},
],
};
});
/**
* 🧠 Handler para el prompt "summarize_notes".
*/
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
if (request.params.name !== "summarize_notes") {
throw new Error("Unknown prompt");
}
const embeddedNotes = Object.entries(notes).map(([id, note]) => ({
type: "resource" as const,
resource: {
uri: `note:///${id}`,
mimeType: "text/plain",
text: note.content,
},
}));
return {
messages: [
{
role: "user",
content: {
type: "text",
text: "Please summarize the following notes:",
},
},
...embeddedNotes.map((note) => ({
role: "user" as const,
content: note,
})),
{
role: "user",
content: {
type: "text",
text: "Provide a concise summary of all the notes above.",
},
},
],
};
});
/**************** Fin de la configuración del servidor MCP ****************/
/**
* Endpoint principal MCP (POST).
*/
app.post("/mcp", async (req, res) => {
console.log("📨 Recibida petición MCP POST");
console.log("📦 Cuerpo de la petición:", req.body);
try {
// Busca sessionId en cabecera
const sessionId = req.headers["mcp-session-id"] as string | undefined;
console.log(`🔑 Procesando para session ID: ${sessionId}`);
let transport: StreamableHTTPServerTransport;
if (sessionId && transports[sessionId]) {
console.log(`🔄 Reutilizando transport para sesión ${sessionId}`);
transport = transports[sessionId];
} else if (!sessionId && isInitializeRequest(req.body)) {
console.log("🆕 Sin session ID, inicializando nuevo transport");
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sessionId) => {
transports[sessionId] = transport;
},
});
transport.onclose = () => {
if (transport.sessionId) {
delete transports[transport.sessionId];
}
};
await server.connect(transport);
} else {
res.status(400).json({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Bad Request: No valid session ID provided",
},
id: req?.body?.id,
});
return;
}
// Maneja la petición con el transport correspondiente
await transport.handleRequest(req, res, req.body);
} catch (error) {
console.error("❌ Error manejando petición MCP:", error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: "2.0",
error: {
code: -32603,
message: "Internal server error",
},
id: req?.body?.id,
});
return;
}
}
});
/**
* Endpoint GET para SSE streams (usado por MCP para eventos).
*/
app.get("/mcp", async (req: Request, res: Response) => {
console.error("📥 Recibida petición MCP GET");
const sessionId = req.headers["mcp-session-id"] as string | undefined;
if (!sessionId || !transports[sessionId]) {
res.status(400).json({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Bad Request: No valid session ID provided",
},
id: req?.body?.id,
});
return;
}
const lastEventId = req.headers["last-event-id"] as string | undefined;
if (lastEventId) {
console.error(`🔁 Cliente reconectando con Last-Event-ID: ${lastEventId}`);
} else {
console.error(`🌐 Estableciendo nuevo SSE para sesión ${sessionId}`);
}
const transport = transports[sessionId];
await transport!.handleRequest(req, res);
});
/**
* Endpoint DELETE para terminar sesión MCP.
*/
app.delete("/mcp", async (req: Request, res: Response) => {
const sessionId = req.headers["mcp-session-id"] as string | undefined;
if (!sessionId || !transports[sessionId]) {
res.status(400).json({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Bad Request: No valid session ID provided",
},
id: req?.body?.id,
});
return;
}
console.error(
`🗑️ Recibida petición de terminación de sesión para ${sessionId}`
);
try {
const transport = transports[sessionId];
await transport!.handleRequest(req, res);
} catch (error) {
console.error("❌ Error al terminar sesión:", error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: "2.0",
error: {
code: -32603,
message: "Error handling session termination",
},
id: req?.body?.id,
});
return;
}
}
});
/**
* 🚦 Inicia el servidor Express.
*/
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`📡 MCP Streamable HTTP Server escuchando en puerto ${PORT}`);
});
/**
* 🛑 Maneja el apagado del servidor y limpia recursos.
*/
process.on("SIGINT", async () => {
console.log("🛑 Apagando servidor...");
// Cierra todos los transports activos
for (const sessionId in transports) {
try {
console.log(`🔒 Cerrando transport para sesión ${sessionId}`);
await transports[sessionId].close();
delete transports[sessionId];
} catch (error) {
console.error(`❌ Error cerrando transport para sesión ${sessionId}:`, error);
}
}
console.error("✅ Apagado completo");
process.exit(0);
});
También le he añadido la configuración para usarlo dentro de Visual Studio Code con GitHub Copilot Chat:
{
"servers": {
"mcp-low-level-server-streamable-http": {
"type": "http",
"url": "http://localhost:3001/mcp",
}
}
}Mi proyecto de ejemplo con estos cambios puedes encontrarlo en este repo de mi cuenta de GitHub: https://github.com/0GiS0/mcp-low-level-server-streamable-http
¡Nos vemos 👋🏻!
