simple-mcp-basics
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@simple-mcp-basicsAdd 23 and 19 using the sumar tool."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP básico con TypeScript
Ejemplo pequeño pero completo de Model Context Protocol (MCP): un servidor local, un cliente y una demostración ejecutable de las tres primitivas principales del servidor.
Tools: acciones que un modelo puede decidir invocar.
Resources: datos de solo lectura que una aplicación cliente obtiene por URI.
Prompts: plantillas de mensajes que el usuario o cliente puede seleccionar.
El proyecto evita deliberadamente bases de datos, frameworks web, autenticación y llamadas a un LLM. El objetivo es que se vea el protocolo sin ruido adicional y que el código pueda servir como punto de partida.
Requisitos
Node.js 20 o posterior
npm
Related MCP server: MCP AI Chat LangChain
Ejecutar la demo
npm install
npm run demoNo hay que iniciar el servidor aparte. El cliente lo lanza como subproceso, se conecta por stdio, hace el handshake MCP y lo cierra al terminar.
La salida incluye, en este orden:
Descubrimiento de
sumarmediantelistTools()y ejecución concallTool().Descubrimiento de
info://appmediantelistResources()y lectura conreadResource().Descubrimiento de
explicar-conceptomediantelistPrompts()y renderizado congetPrompt().
También se puede comprobar el tipado y generar JavaScript:
npm run check
npm run buildMapa del proyecto
src/
├── server.ts # declara tools, resources y prompts; atiende por stdio
└── client.ts # inicia el server, descubre capacidades y las consumeQué ocurre al ejecutar el cliente
npm run demo
│
▼
Client + StdioClientTransport
│ crea el proceso y usa stdin/stdout
▼
McpServer + transporte stdio
│
├── tools/list ──► definición y JSON Schema de `sumar`
├── tools/call ──► ejecuta `sumar`
├── resources/list ──► metadatos de `info://app`
├── resources/read ──► contenido del resource
├── prompts/list ──► metadatos de `explicar-concepto`
└── prompts/get ──► mensajes de la plantillaclient.connect(transport) realiza primero el handshake initialize: cliente y servidor intercambian versión, identidad y capacidades. Después, el SDK presenta métodos TypeScript de alto nivel; por debajo viajan mensajes JSON-RPC de MCP.
Tool
sumar ilustra una operación. Su esquema Zod tiene tres trabajos: documenta los argumentos, genera el JSON Schema que descubre el cliente y valida el input antes de ejecutar el handler.
En un sistema real, un tool podría consultar una API, crear un ticket o ejecutar una operación de negocio. Debe tener un nombre estable, una descripción precisa y un esquema estricto.
Resource
info://app ilustra información direccionable y de solo lectura. La lista contiene metadatos; el contenido se obtiene en una llamada separada usando la URI.
En un sistema real, un resource podría representar documentación, configuración, el esquema de una base de datos o un registro. Para colecciones variables, el SDK también ofrece ResourceTemplate con URIs como customer://{id}.
Prompt
explicar-concepto recibe argumentos y produce mensajes. No llama por sí mismo a un LLM: un host con un modelo podría tomar esos mensajes y enviárselos.
En un sistema real, un prompt puede estandarizar flujos como “analizar incidente”, “resumir cliente” o “preparar revisión”. A diferencia de un tool, normalmente lo selecciona explícitamente el usuario o la aplicación.
Responsabilidades: host, cliente y servidor
El servidor MCP publica capacidades y ejecuta sus handlers.
El cliente MCP mantiene una conexión y traduce operaciones del protocolo a métodos como
listTools().El host es la aplicación completa (un IDE o asistente, por ejemplo). Puede contener el cliente, mostrar resources/prompts y permitir que un modelo elija tools.
Este repositorio implementa servidor y cliente, pero no un host con LLM. Por eso la demo llama sumar directamente: hace visible el mecanismo MCP sin depender de una API de IA.
Cómo extender este template
Mantener
createServer()independiente del transporte.Registrar cada capacidad con un nombre, una descripción y schemas claros.
Mover integraciones reales a módulos de dominio; los handlers MCP deberían ser adaptadores pequeños.
Añadir manejo de errores esperado con resultados que incluyan
isError: true.Añadir tests del servidor con un transporte en memoria antes de introducir HTTP.
Usar Streamable HTTP cuando el servidor deje de ser un proceso local y deba atender conexiones remotas; ahí también habrá que diseñar autenticación, sesiones y despliegue.
Regla importante de stdio
stdout es el canal del protocolo. Cualquier console.log() en el servidor puede corromper los mensajes JSON-RPC. Los logs del servidor deben enviarse a stderr con console.error(). El cliente sí puede imprimir normalmente su propia salida.
Referencias oficiales
Available Tools
1 toolsumarSumar dos numerosA
Suma dos numeros y devuelve el resultado.
| Name | Required | Description | Default |
|---|---|---|---|
| a | Yes | Primer sumando | |
| b | Yes | Segundo sumando |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are present, so the description carries the burden of behavioral disclosure. It states that the operation adds and returns a result, which implies a pure, side-effect-free computation, but it does not disclose edge cases, error behavior, or type handling. The description provides basic transparency without rich behavioral detail.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single compact sentence that front-loads the action and states the output. Every word earns its place, with no redundancy or unnecessary detail.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple two-number addition tool with fully documented parameters, the description is nearly complete: it states the operation, the inputs are clear from the schema, and the result is mentioned. A more explicit return type or an example would improve completeness, but nothing essential is missing for correct invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, with both parameters documented as 'Primer sumando' and 'Segundo sumando'. The description adds no parameter-specific semantics beyond what the schema already provides, so the baseline score of 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Suma') and resource ('dos numeros'), and explicitly states that it returns the result. With no sibling tools to differentiate from, the purpose is unambiguous and immediately actionable.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies when to use the tool: whenever two numbers need to be added. However, it provides no explicit when-to-use or when-not-to-use guidance, and there are no sibling alternatives described. For a simple arithmetic tool, the implied usage is adequate but not fully explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
1 tool update
v1.0.0- First observed
sumar
TDQS
Scored across 1 tool
With only one tool, there is no possibility of confusion. The name 'sumar' clearly indicates the addition operation, so an agent can easily identify its purpose.
A single tool is trivially consistent in naming. While it uses a lone verb rather than a verb-noun pattern, there are no other tools to compare against, so consistency is perfect.
The server exposes only one tool that performs a trivial arithmetic operation, which fits the description of a 'single trivial tool' and is an extreme mismatch for a tool set.
The server is named 'basics' but only offers addition. Obvious missing operations like subtraction, multiplication, and division leave the surface severely incomplete for even basic arithmetic.
Maintenance
Related MCP Connectors
Model Context Protocol server for the Apideck Unified API. Connect any MCP-compatible agent framework to 100+ accounting systems, HRIS platforms, file storage providers, and more through one integration. More information https://www.apideck.com/mcp-server
MCP server for progressive tool usage at any scale (see https://klavis.ai)
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA stateless Model Context Protocol server that implements a simple echo functionality with resource, tool, and prompt components, enabling LLMs to echo back messages through standardized MCP interactions.1-
- FlicenseNot gradedqualityDmaintenanceA basic Model Context Protocol server implementation that demonstrates core functionality including tools and resources for AI chat applications.-
- AlicenseNot gradedqualityDmaintenanceA minimal demonstration server showcasing MCP protocol capabilities including tools, resources, and prompts with basic examples like hello world functionality.1 npmMIT
- AlicenseNot gradedqualityDmaintenanceA minimal learning-focused MCP server that demonstrates core primitives like tools and resources through simple greeting functions. It provides a foundational example for connecting AI models to external data using both Streamable HTTP and stdio transports.10 npmMIT