Skip to main content
Glama

MCP 服务器和客户端示例 (TypeScript)

该项目演示了使用 TypeScript 和@modelcontextprotocol/sdk创建和交互简单的模型上下文协议 (MCP) 服务器和独立的 MCP 客户端。

设置包括:

  1. my-mcp-greeter-server :提供与问候相关的工具、资源和提示的 MCP 服务器。

  2. my-mcp-client-script :一个简单的命令行客户端脚本,用于启动服务器、连接服务器并以编程方式与其功能进行交互。

本例中客户端和服务器之间的通信使用**stdio(标准输入/输出)**传输机制。

流程概述

该项目建设主要分为以下几个阶段:

  1. 服务器开发:创建 MCP 服务提供商。

  2. 客户端开发:创建脚本来使用服务器的服务。

  3. 测试和交互:运行客户端脚本,启动服务器并演示通信。

  4. (可选)集成:讨论如何将服务器与现有的 MCP 客户端(如 VS Code 扩展)集成。

Related MCP server: TypeScript MCP Server Boilerplate

先决条件

开始之前,请确保已安装以下软件:

  • Node.js (建议使用 v16 或更高版本)

  • npm (通常包含在 Node.js 中)

  • 文本编辑器或 IDE(如 VS Code)

  • npx (通常包含在 npm 中)——适用于使用 MCP Inspector 进行测试。

第一阶段:搭建 MCP 服务器 ( my-mcp-greeter-server )

  1. 项目设置:

    • 创建了目录my-mcp-greeter-server 。

    • 初始化一个 npm 项目: npm init -y 。

    • 安装了必要的依赖项: npm install @modelcontextprotocol/sdk zod 。

    • 已安装开发依赖项: npm install -D typescript @types/node 。

    • 初始化 TypeScript 配置: npx tsc --init 。

    • 配置tsconfig.json (设置"module": "Node16" 、 "target": "ES2022" 、 "outDir": "./build" 、 "rootDir": "./src"等)。

    • 更新了package.json以包含"type": "module"并添加了build / start脚本。

    • 创建源文件src/index.ts 。

  2. 服务器实现( src/index.ts ) :

    • 导入所需的模块( McpServer 、 StdioServerTransport 、 z )。

    • 定义服务器name和version的常量。

    • 实例化McpServer ,传递名称、版本并声明其功能(工具、资源、提示)。

    • 定义了一个工具 ( greet ) :使用server.tool()创建了一个可供客户端调用的函数。其中包含描述,使用 Zod 定义了输入参数 ( name , politeness ),并实现了处理程序以返回个性化的问候字符串。

    • 定义了一个资源 ( server-info ) :使用server.resource()暴露静态数据。提供了一个唯一的 URI ( info://greeter/about ),并实现了处理程序以返回服务器的名称和版本。

    • 定义了一个提示 ( suggest-greeting ) :使用server.prompt()创建了一个可重用的交互模板。模板中包含了描述,并实现了处理程序,用于返回一组预定义的用户/助手消息,以指导 LLM 交互。

    • 使用 Stdio Transport :实例化StdioServerTransport作为通信方法。

    • 已连接:调用await server.connect(transport)以使服务器准备就绪。

    • 日志记录:添加了console.error语句以便在执行期间可见,这对于使用 stdout 来传输协议消息的 stdio 传输尤其重要。

    • 保持活动:确保 Node.js 进程在连接后不会立即退出。

  3. 建筑与修缮:

    • 运行npm run build在build目录中将 TypeScript 编译为 JavaScript。

    • 修复了与直接访问服务器版本相关的 TypeScript 错误,选择使用预定义常量。

第 2 阶段:构建 MCP 客户端脚本 ( my-mcp-client-script )

  1. 项目设置:

    • 创建了一个单独的目录my-mcp-client-script 。

    • 初始化一个 npm 项目: npm init -y 。

    • 安装了必要的依赖项: npm install @modelcontextprotocol/sdk 。

    • 已安装开发依赖项: npm install -D typescript @types/node 。

    • 与服务器项目类似初始化并配置tsconfig.json 。

    • 使用"type": "module"和build / start脚本更新了package.json 。

    • 创建源文件src/client-script.ts 。

  2. 客户端实现( src/client-script.ts ) :

    • 导入所需的模块( Client , StdioClientTransport , path , url )。

    • 确定的服务器路径:计算服务器编译的index.js文件的路径(相对或绝对)。

    • 配置 Stdio Transport :实例化StdioClientTransport ,提供command ( node )和args (服务器脚本的路径)。此配置至关重要,因为客户端传输会启动服务器进程。

    • 实例化客户端:创建一个Client实例,赋予它一个身份并声明其使用工具和资源的意图。

    • Connected :调用await client.connect(transport) ,启动服务器进程并通过其 stdio 流建立 MCP 连接。

    • 与服务器交互:

      • 使用await client.callTool()调用greet工具。

      • 使用await client.readResource()读取server-info资源。

      • 使用await client.getPrompt()获取suggest-greeting提示。

    • 记录结果:使用console.log显示从服务器收到的响应。

    • 关闭连接:在finally块中使用await client.close()来彻底关闭连接并终止服务器进程。

第三阶段:构建和运行

  1. 构建两个项目:

    • cd my-mcp-greeter-server && npm run build

    • cd ../my-mcp-client-script && npm run build

  2. 运行客户端:

    • cd my-mcp-client-script

    • npm run start (或node build/client-script.js )

    • 观察客户端( console.log )和服务器( console.error )的交叉输出,确认工具/资源/提示的通信和执行成功。

角色说明

  • 服务器( GreeterServer ) :

    • 提供服务:公开特定功能(问候工具、服务器信息、提示模板)。

    • 被动监听器(在 stdio 中) :等待客户端通过其标准流进行连接。

    • 执行逻辑:当客户端请求时运行与工具/资源/提示相关的代码。

    • 发送结果:根据 MCP 规范格式化结果并将其发送回客户端。

  • 客户端( client-script.ts ) :

    • 使用服务:使用服务器提供的功能。

    • 发起程序(在 stdio 中) :启动服务器进程并建立连接。

    • 发送请求:决定调用哪个工具、读取哪个资源或获取哪个提示,并发送适当的 MCP 请求。

    • 接收结果:处理服务器发回的响应。

    • 控制流:管理交互的顺序并决定何时关闭连接。

交互式测试服务器

当客户端脚本测试程序交互时,您可以使用 MCP 检查器单独测试服务器的功能:

# Make sure the server is NOT already running
# Replace /path/to/... with the actual absolute path
npx @modelcontextprotocol/inspector node /path/to/my-mcp-greeter-server/build/index.js

Available Tools

1 tool
greetB

Generates a personalized greeting.

NameRequiredDescriptionDefault
nameYesThe name of the person to greet.
politenessNoDesired politeness level.informal

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'personalized greeting' but doesn't explain what that entails (e.g., format, length, language), whether it's idempotent, or any side effects. This leaves significant gaps in understanding the tool's behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with a single sentence that directly states the tool's purpose. There is no wasted language, and it is front-loaded with the essential information, making it efficient and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (2 parameters, no output schema, no annotations), the description is minimally adequate. However, it lacks details on the greeting format or any behavioral context, which would be helpful for an agent to use it effectively, especially without annotations.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, so the schema already fully documents both parameters (name and politeness). The description adds no additional meaning beyond what the schema provides, such as examples or edge cases, meeting the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Generates') and resource ('a personalized greeting'), making it immediately understandable. However, since there are no sibling tools, it doesn't need to differentiate from alternatives, which prevents a perfect score of 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives, prerequisites, or any contextual constraints. It simply states what the tool does without offering usage instructions or exclusions.

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. 1 tool updatev1.0.0
    • First observedgreet

TDQS

B3.2/5.0

Scored across 1 tool

Disambiguation5/5

With only one tool, there is no possibility of confusion or overlap between tools, making disambiguation perfect. The tool's purpose is clearly distinct by default.

Naming Consistency5/5

A single tool inherently follows a consistent naming pattern, as there are no other tools to compare it against. The name 'greet' is straightforward and appropriate.

Tool Count2/5

One tool is too few for most server purposes, as it limits functionality and suggests an incomplete or trivial implementation. This is borderline for a meaningful MCP server scope.

Completeness1/5

The server's purpose is unclear from the single tool, but 'greet' alone suggests severe incompleteness for any practical domain. There are obvious gaps, as no other operations are supported, making the surface inadequate.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    D
    quality
    D
    maintenance
    A minimal Model Context Protocol server in TypeScript that demonstrates MCP-compliant resources and tools for LLMs, featuring simple resources and a basic tool that echoes messages or returns greetings.
    1
    5
    Apache 2.0
  • A
    license
    B
    quality
    D
    maintenance
    A boilerplate project for quickly developing Model Context Protocol (MCP) servers using TypeScript SDK. Includes example tools like calculator and greeting functions, plus system information resources.
    3
    ISC
  • A
    license
    B
    quality
    D
    maintenance
    A demonstration TypeScript MCP server that showcases basic MCP concepts with simple tools (greeting, calculator), text resources, and prompt templates for learning the Model Context Protocol.
    2
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    A boilerplate project for quickly developing Model Context Protocol (MCP) servers using TypeScript SDK, with example implementations of tools (calculator, greeting) and resources (server info).
    452 npm
    MIT