使用 TypeScript 建立自己的 MCP Server

前言

近來 MCP 和各種 AI 工具快速發展,為了更了解 MCP 是什麼,決定動手實作一個簡單的 MCP Server。這篇文章算是自己的快速紀錄,一方面釐清 MCP 的基本概念,另一方面整理一下如何用 TypeScript 實際建立並測試 MCP Server,方便未來回顧使用。

什麼是 MCP?

MCP(全名 Model Context Protocol)是一種「給 AI 模型用的互動式 API 標準」。

可以想成:平常會寫 REST API 給使用者或前端呼叫,而 MCP 是「給大型語言模型(LLM)使用的 API 協定」,目的就是讓 AI 模型能用統一且標準化的方式:

  • 取得外部資料(例如:最新新聞、查天氣、查匯率)

簡單來說:MCP Server 就是讓你的伺服器可以被 AI 視為一個「工具」或「可讀取的資料來源」,並透過標準協定互動。

建立 MCP 專案

從零開始建立一個 MCP Server 的專案環境。專案會用 TypeScript 開發,並搭配幾個常見的套件來幫忙處理型別驗證、API 請求等工作。整體結構會很簡單,主要目的是讓 MCP Server 能提供一個「查新聞」的小工具,讓 AI 模型可以透過 MCP 協定來呼叫它

步驟一:建立專案資料夾

  1. 打開 VSCode
  2. 新建資料夾例如 mcp-demo

步驟二:安裝套件

1
2
3
4
npm init -y
npm install @modelcontextprotocol/sdk zod axios
npm install -D typescript @types/node
npx tsc --init

各個安裝套件的用途說明:

  • @modelcontextprotocol/sdk:MCP 官方開發套件,提供建立 Server、註冊工具與資源的能力
  • zod:一個強型別驗證工具,用來定義和驗證輸入資料的結構

步驟三:建立 index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import axios from "axios";

const server = new McpServer({
name: "Demo",
version: "1.0.0",
});

// 新聞標題工具,支援 query 主題
server.tool(
"news_headlines",
{ query: z.string().optional() },
async ({ query }) => {
const url = new URL("https://newsapi.org/v2/everything");
if (query) url.searchParams.set("q", query);
url.searchParams.set("apiKey", "YOUR_API_KEY");

const { data } = await axios.get(url.toString());

if (!data.articles?.length) {
return {
content: [{ type: "text", text: "找不到新聞結果..." }],
};
}

const article = data.articles[0];

return {
content: [
{
type: "text",
text: `${article.title}
${article.url}`,
},
],
};
}
);

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

步驟四:執行 MCP Server

編譯後執行

1
npx tsc

測試 MCP Server

使用 MCP inspector 來測試你的 Server:

1
npx @modelcontextprotocol/inspector node index.js
  • 測試 tool: news 輸入 { query: "trump" } 應該會回傳相關新聞

picture 9


在 VS Code 中使用 Cline

設定好 MCP Server 之後,我們可以透過 Cline—一款支援 Claude 開發的 VS Code 擴充套件—來測試我們的 MCP Server 是否運作正常

下圖是我在 VS Code 中啟動 Cline 並設定好 MCP Server 的畫面:
picture 7

只要在 Cline 中輸入簡單的 Prompt,像是「給我 Trump 的新聞」,你會發現 Cline 背後會自動呼叫 MCP Server,並使用我們先前實作的 news_headlines 工具來回應這個需求,從外部新聞 API 取得結果,然後返回給模型使用:
picture 8

透過這個方式,我們就能模擬 LLM 如何與我們建立的工具互動,並確認 MCP Server 的功能是否如預期運作。

總結

這裡實際用 TypeScript SDK 建立了一個 MCP Server,實作了 news 工具來查詢新聞資料。

在開發完成後,使用 MCP Inspector 測試 Server 的功能是否正確,最後再介紹如何透過 VS Code 的 Cline 擴充套件,模擬 Claude 等 LLM 工具呼叫 MCP Server 的情境。

這樣的整合方式,應該可以快速驗證 MCP 工具與資源的設計是否符合實際需求。

未來如果要打造更多可與 AI 模型互動的應用,這套流程會是一個實用可延伸的基礎。再進一步嘗試整合其他 API 或資料來源,建立更完整的服務。

Reference