首页
/ 【亲测免费】 MCP TypeScript SDK 使用教程

【亲测免费】 MCP TypeScript SDK 使用教程

2026-01-30 04:49:25作者:宣利权Counsellor

1. 项目介绍

Model Context Protocol (MCP) TypeScript SDK 是一个开源项目,旨在为 Model Context Protocol 提供一个类型安全的 TypeScript 实现。它允许开发者构建能够向大型语言模型(LLM)应用程序提供数据和功能的标准化服务器。通过 MCP,开发者可以创建支持多种传输方式的服务器,如标准输入输出(stdio)和基于 HTTP 的服务器发送事件(SSE),并且可以轻松地处理 MCP 协议消息和生命周期事件。

2. 项目快速启动

以下是一个快速启动 MCP 服务器的示例代码:

import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
import { z } from "zod";

// 创建一个 MCP 服务器
const server = new McpServer({
  name: "Demo",
  version: "1.0.0"
});

// 添加一个加法工具
server.tool("add", {
  a: z.number(),
  b: z.number()
}, async ({ a, b }) => ({
  content: [
    { type: "text", text: String(a + b) }
  ]
}));

// 添加一个动态问候资源
server.resource("greeting", new ResourceTemplate("greeting://{name}", { list: undefined }), async (uri, { name }) => ({
  contents: [
    { uri: uri.href, text: `Hello, ${name}!` }
  ]
}));

// 开始接收 stdin 消息并发送 stdout 消息
const transport = new StdioServerTransport();
await server.connect(transport);

确保你已经通过 npm 安装了 @modelcontextprotocol/sdk

npm install @modelcontextprotocol/sdk

3. 应用案例和最佳实践

Echo 服务器

创建一个简单的 Echo 服务器,将接收到的消息原样返回:

// Echo 服务器工具
server.tool("echo", {
  message: z.string()
}, async ({ message }) => ({
  content: [
    { type: "text", text: message }
  ]
}));

SQLite 浏览器

创建一个工具来查询 SQLite 数据库并返回结果:

// SQLite 查询工具
server.tool("query-sqlite", {
  query: z.string()
}, async ({ query }) => {
  // 这里应该包含对 SQLite 数据库的查询逻辑
  const result = "查询结果"; // 假设的查询结果
  return {
    content: [
      { type: "text", text: result }
    ]
  };
});

测试和调试

为了测试和调试 MCP 服务器,可以使用内置的测试框架和工具,例如 jest

// jest 配置
jest.config({
  // jest 配置项
});

4. 典型生态项目

MCP TypeScript SDK 的生态系统中有许多项目,例如:

  • @modelcontextprotocol/cli:命令行工具,用于启动和调试 MCP 服务器。
  • @modelcontextprotocol/sdk-browser:浏览器版本的 SDK,用于在浏览器中创建 MCP 客户端。
  • @modelcontextprotocol/examples:包含多个使用 MCP SDK 的示例项目。

通过这些项目和工具,开发者可以更轻松地构建与 LLM 应用程序交互的复杂系统。

登录后查看全文
热门项目推荐
相关项目推荐