MCP TypeScript SDK
MCP TypeScript SDK
Обзор
Протокол контекста модели (MCP) позволяет приложениям предоставлять контекст для LLM стандартизированным способом, разделяя задачи предоставления контекста и фактического взаимодействия с LLM.
Этот репозиторий содержит реализацию TypeScript SDK спецификации MCP. Он работает на Node.js, Bun и Deno и включает:
Библиотеки MCP сервера (инструменты/ресурсы/подсказки, Streamable HTTP, stdio, вспомогательные средства аутентификации)
Библиотеки MCP клиента (транспорты, высокоуровневые вспомогательные средства, вспомогательные средства OAuth)
Опциональные пакеты промежуточного ПО для конкретных сред выполнения/фреймворков (Express, Fastify, Hono, Node.js HTTP)
Рабочие примеры (в папке
examples/)
Related MCP server: MCP - Model Context Protocol TypeScript SDK
Пакеты
Этот монорепозиторий публикует раздельные пакеты:
@modelcontextprotocol/server: создание MCP серверов@modelcontextprotocol/client: создание MCP клиентов
Схемы инструментов и подсказок используют Standard Schema — используйте Zod v4, Valibot, ArkType или любую совместимую библиотеку.
Они представляют собой намеренно тонкие адаптеры: они не должны добавлять новую функциональность MCP или бизнес-логику. Подробнее см. в packages/middleware/README.md.
@modelcontextprotocol/node: обертка транспорта Node.js Streamable HTTP дляIncomingMessage/ServerResponse@modelcontextprotocol/express: вспомогательные средства Express (настройки приложения по умолчанию + валидация заголовка Host)@modelcontextprotocol/fastify: вспомогательные средства Fastify (настройки приложения по умолчанию + валидация заголовка Host)@modelcontextprotocol/hono: вспомогательные средства Hono (настройки приложения по умолчанию + хук парсинга JSON тела + валидация заголовка Host)
Установка
Сервер
npm install @modelcontextprotocol/server
# or
bun add @modelcontextprotocol/server
# or
deno add npm:@modelcontextprotocol/serverКлиент
npm install @modelcontextprotocol/client
# or
bun add @modelcontextprotocol/client
# or
deno add npm:@modelcontextprotocol/clientОпциональные пакеты промежуточного ПО
SDK также публикует опциональные пакеты "промежуточного ПО", которые помогают вам подключить MCP к конкретной среде выполнения или веб-фреймворку (например, Express, Fastify, Hono или Node.js http).
Эти пакеты являются намеренно тонкими адаптерами и не должны добавлять дополнительные функции MCP или бизнес-логику. Подробнее см. в packages/middleware/README.md.
# Node.js HTTP (IncomingMessage/ServerResponse) Streamable HTTP transport:
npm install @modelcontextprotocol/node
# Express integration:
npm install @modelcontextprotocol/express express
# Fastify integration:
npm install @modelcontextprotocol/fastify fastify
# Hono integration:
npm install @modelcontextprotocol/hono honoНачало работы
Вот как выглядит MCP сервер. Этот минимальный пример предоставляет один инструмент greet через stdio:
import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
const server = new McpServer({ name: 'greeting-server', version: '1.0.0' });
server.registerTool(
'greet',
{
description: 'Greet someone by name',
inputSchema: z.object({ name: z.string() })
},
async ({ name }) => ({
content: [{ type: 'text', text: `Hello, ${name}!` }]
})
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main();Готовы создать что-то реальное? Следуйте пошаговым руководствам:
Создайте свой первый сервер — сервер погодных оповещений через stdio, от
npm initдо вызова инструментаСоздайте свой первый клиент — подключитесь к этому серверу, выведите список его инструментов и вызовите их
Для рабочих сквозных примеров, выходящих за рамки руководств, смотрите:
examples/README.md— рабочие, самопроверяемые пары примеров клиент/сервер (одна история на каталог)
Документация
Создание сервера — ваш первый MCP сервер, шаг за шагом
Создание клиента — ваш первый MCP клиент, шаг за шагом
Сайт документации — полные руководства: инструменты, ресурсы, подсказки, обслуживание через HTTP и stdio, клиенты, OAuth и миграция
Устранение неполадок — распространенные ошибки и их решения
Локальная сборка документации
Для работы над сайтом документации локально:
pnpm docs:api # Generate the API reference markdown (output: docs/api/)
pnpm docs:dev # Start the VitePress dev server for the V2 site
pnpm docs:build # Build the V2 site (output: docs/.vitepress/dist/)
pnpm docs:multi # Build the combined V1 + V2 site (output: tmp/docs-combined/)This server cannot be deployed
Maintenance
Related MCP Connectors
A simple Typescript MCP server built using the official MCP Typescript SDK and smithery/cli. This…
A TypeScript MCP server for Home Assistant, enabling programmatic management of entities, automati…
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
The Mercado Pago MCP Server implements the Model Context Protocol to provide AI agents and LLMs with access to Mercado Pago's APIs and tools within compatible development environments. It acts as an intermediary that translates Mercado Pago resources into executable functions (tools) that AI applications can invoke to perform actions and automate flows. The server simplifies integration, enables using documentation to implement or improve code, and optimizes operations through natural language interactions without manual implementations.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA TypeScript framework for building Model Context Protocol (MCP) servers with automatic discovery and loading of tools, resources, and prompts.12 npm-
- AlicenseNot gradedqualityDmaintenanceA TypeScript wrapper library for the Model Context Protocol SDK that provides a simplified interface for creating MCP servers with tools, resources, and prompts without needing to work directly with the protocol.19 npmAGPL 3.0
- AlicenseAqualityDmaintenanceA starter project for rapidly developing Model Context Protocol servers using TypeScript and the official SDK. It includes pre-implemented examples of tools and resources to help developers jumpstart their custom MCP server development.6ISC
- AlicenseBqualityDmaintenanceA TypeScript MCP server boilerplate providing example tools and resources for rapid development of custom Model Context Protocol servers.8ISC