wen aidev
Published on

MCP Server 開發02 實作 簡單的數學運算MCP

概要

這篇文章開發Mcp server 本地端最簡單的數學加減功能 Sum,Subtraction
github code: github code 簡單的數學mcp server

Winsurf MCP 測試截圖

Winsurf 中的 MCP Server 測試結果

官方SDK

MCP server 官方有提供各種程式語言的SDK幫助開發
官方SDK
官方document

這篇是基於Typescript 當範例開發簡單的數學計算
官方 TypeScript SDK
如果是 python 可以參考:
(https://www.bilibili.com/video/BV1RNTtzMENj/?spm_id_from=333.999.0.0)

說明

是可以直接把官方github 加文件 貼給cursor 或是AI ide 下prompt 直接開發 MCP server 是可行的,基本上要自動修正幾次錯誤才能成功.
所以最快開發過是,知道概念=>叫AI開發MCP=>遇到問題在查看文件針對修正.

最簡化mcp server sdk開發過程

>1.實例化一個`server`
  const `server` = new McpServer( )
>2.加上 tools
`server`.tool( )
>3 加上 Resources
`server`.Resources( )
>tool =給使用者的工具 ,Resources=靜態的說明 可理解為http get
>4.運行 server

當然實務上應用開發會複雜多,可能需要串聯資料庫等

基本概念和TypeScript SDK 功能介紹

MCP 架構圖

MCP 整體架構

MCP 詳細架構圖

MCP 詳細架構

官方 TypeScript SDK

主要組件 server

McpServer

Server 實例化分兩種 二選一就好

1. 高層級 API:McpServer

官方推薦使用 McpServer 類別,提供便利的開發體驗:

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new McpServer({
  name: 'example-server',
  version: '1.0.0',
});

2. 低層級 API:Server

需要更多控制時可使用基礎 Server 類別:

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
  ListToolsRequestSchema,
  CallToolRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

const server = new Server(
  {
    name: 'example-server',
    version: '1.0.0',
  },
  {
    capabilities: { tools: {} },
  },
);

傳輸方式

傳輸方式

這就是上一章說的1.local 2.Remote services(線上服務)

1. StdioServerTransport(local)

import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const transport = new StdioServerTransport();
await server.connect(transport);

2. StreamableHTTPServerTransport(Remote services)

import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
// 適用於 Web 服務部署

3. SSEServerTransport(Remote services已棄用)

SSE 是之前預設 後來改成 streamhttp,所以還是會看到之前的MCP 上面寫SSE

import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
// 僅向後兼容,新專案不建議使用

MCP支援的4個功能

Winsurf MCP 測試截圖

MCP支援的功能

  1. Tools:讓 AI 執行 function call
    ex:讓 AI 執行程式邏輯,例如查天氣、下訂單
  2. Resources:提供查資料用的
    context(文件、資料庫、API) > 是靜態資料 簡而言之就是說明而已

  1. Prompts:預定義的提示範本
  2. Sampling:控制Ai生成風格
    生成內容的控制參數(溫度、top_p等)
    參考:AI Temperature、Top-P 和 Top-K 參數

MCP 不只是調用工具而已,還可以利用 prompts和Sampling控制ai 回覆的內容.

Client API

SDK 也提供 Client 端 API 用於連接 MCP 伺服器:

import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

const client = new Client({ name: 'client', version: '1.0.0' });
await client.connect(transport);

// 呼叫工具
const result = await client.callTool({
  name: 'example-tool',
  arguments: { arg1: 'value' },
});

開發環境設置

以下可以用cursor 之類直接自動安裝,只要知道有這些就好.

系統需求驗證

TypeScript MCP Server 開發需要 Node.js 16 或更高版本:

node --version  # 應顯示 v16.0.0 或更高
npm --version   # 確認 npm 可用

創建項目結構

創建簡單的數學運算 MCP Server:

# 創建項目目錄
mkdir math-mcp-server
cd math-mcp-server

# 初始化 npm 項目
npm init -y

# 安裝核心依賴
npm install @modelcontextprotocol/sdk zod

# 安裝開發依賴
npm install -D @types/node typescript

# 創建源碼目錄
mkdir src
touch src/index.ts

配置 package.json

package.json 中添加必要的配置:

{
  "name": "math-mcp-server",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "math-server": "./build/index.js"
  },
  "scripts": {
    "build": "tsc && chmod 755 build/index.js",
    "dev": "tsc --watch",
    "start": "node build/index.js"
  },
  "files": ["build"],
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.0.0",
    "zod": "^3.22.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "typescript": "^5.0.0"
  }
}

TypeScript 配置

創建 tsconfig.json 配置文件:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "declaration": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "build"]
}

數學運算 加減 MCP Server 實現

以下是我實際開發出來的數學運算 MCP Server 完整程式碼:

github code 簡單的數學mcp server

#!/usr/bin/env node

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';

/**
 * Basic Math MCP Server
 * Provides two mathematical operations: sum and subtraction
 */

// Create the server instance
const server = new McpServer(
  {
    name: 'basic-math-server',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  },
);

// Define the sum tool
server.tool(
  'sum',
  'Add two numbers together',
  {
    a: z.number().describe('First number'),
    b: z.number().describe('Second number'),
  },
  async ({ a, b }: { a: number; b: number }) => {
    const result = a + b;
    return {
      content: [
        {
          type: 'text',
          text: `The sum of ${a} and ${b} is: ${result}`,
        },
      ],
    };
  },
);

// Define the subtraction tool
server.tool(
  'subtraction',
  'Subtract the second number from the first number',
  {
    a: z.number().describe('First number (minuend)'),
    b: z.number().describe('Second number (subtrahend)'),
  },
  async ({ a, b }: { a: number; b: number }) => {
    const result = a - b;
    return {
      content: [
        {
          type: 'text',
          text: `The subtraction of ${b} from ${a} is: ${result}`,
        },
      ],
    };
  },
);

// Start the server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error('Basic Math MCP Server is running on stdio');
}

main().catch((error) => {
  console.error('Server error:', error);
  process.exit(1);
});

建置與測試

編譯專案

# 建置數學運算 Server
npm run build

npm start
# 檢查建置結果
ls -la build/

winsurf Test

因為winsurf mcp介面做的很清楚適合測試,開啟winsurf mcp設定 在mcp_config.json文件加入自己的設定

args 路徑要自己對應實際安裝位置

    "basic-math-server": {
      "command": "node",
      "args": ["C:\\ai研究專用 agent\\mcptest\\build\\index.js"],
      "description": "A basic math server providing sum and subtraction operations"
    }

就可以看到多了mcp工具如下圖:

Winsurf MCP 測試截圖

Winsurf 中的 MCP Server 測試結果

總結

1. MCP 開發概念流程

環境設定創建 McpServer定義工具設定傳輸建置測試

2. MCP 四大核心功能

  • Tools:讓 AI 執行函數調用
  • Resources:提供文件或資料存取
  • Prompts:預定義的提示範本
  • Sampling:AI 內容生成控制

3. 三種傳輸方式

  • StdioServerTransport:標準輸入輸出(推薦)
  • StreamableHTTPServerTransport:HTTP 串流服務
  • SSEServerTransport:伺服器發送事件(已棄用)

支持作者 ☕

台灣用戶:

透過 LINE Pay 支持

國際用戶:

透過 Ko-fi 支持

留言討論