TypeScript 开发AI Agents MCP 完整实战指南(适配 @modelcontextprotocol/sdk 1.29.0)
前言
MCP(Model Context Protocol,模型上下文协议)是大模型、AI Agent、外部工具/数据源统一交互的标准化协议,替代各框架私有 Function Calling,实现工具跨模型、跨项目复用。
本文基于稳定版 @modelcontextprotocol/sdk@1.29.0,全程无废弃API、无TS编译报错,包含完整可运行TS案例、Claude Code官方接入流程、私有NPM包打包发布全流程,适合团队分享落地参考。
一、MCP 核心架构与价值
1.1 核心定位
MCP 采用 Client-Server 分层 STDIO 通信架构,解决传统AI Agent开发碎片化痛点:
- 工具逻辑与大模型推理完全解耦;
- 一套工具同时适配 Claude、GPT、Codex 等所有主流模型;
- 统一管理工具函数、业务资源、提示词模板;
- 强类型约束,TS 编译期拦截参数异常。
1.2 三层核心组件
- MCP Server:能力提供方,注册工具、业务资源,对外标准化输出能力;
- MCP Client:对接大模型应用,负责调用服务端工具、读取上下文资源;
- Host:AI应用主体(Claude Code、自定义Agent、Codex服务),发起工具调用决策。
1.3 三大核心能力
- Tools:可执行函数(时间查询、文本处理、接口请求等);
- Resources:静态业务上下文、知识库、配置文件;
- Prompts:可复用标准化提示模板。
二、环境初始化(零报错配置)
2.1 安装依赖
bash
npm init -y
# 锁定1.29.0稳定SDK
npm install @modelcontextprotocol/sdk@1.29.0 zod
# TS类型与编译工具
npm install typescript ts-node @types/node -D
2.2 tsconfig.json 最终稳定配置(解决Buffer、TS5110报错)
json
# 生成配置文件
npx tsc --init
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"types": ["node"]
},
"include": ["src/**/*"],
"type": "module"
}
2.3 package.json 基础脚本
json
{
"type": "module",
"scripts": {
"build": "tsc",
"dev": "ts-node src/server.ts",
"start": "node dist/client.js"
}
}
三、完整可运行Demo(适配1.29.0,无废弃API)
3.1 MCP服务端 src/server.ts
使用官方推荐 McpServer 高阶API,zod强类型参数校验:
typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// 初始化MCP服务
const server = new McpServer({
name: "ts-custom-mcp-server",
version: "1.0.0"
});
// 工具1:获取当前服务器时间
server.tool(
"get-current-time",
"获取服务器本地标准时间,用于时间类业务判断",
{},
async () => {
return {
content: [{ type: "text", text: new Date().toLocaleString() }]
};
}
);
// 工具2:文本字数统计(zod强类型校验入参)
server.tool(
"count-text-length",
"统计中英文混合文本总字符数",
{ text: z.string().describe("待统计的文本内容") },
async ({ text }) => {
return {
content: [{ type: "text", text: `文本总字数:${text.length}` }]
};
}
);
// 注册业务上下文资源
server.resource(
"agent-common-config",
"biz://agent-common-config",
{ description: "AI通用业务约束上下文" },
async () => {
return {
contents: [
{
uri: "biz://agent-common-config",
text: "回复简洁专业,优先调用工具获取实时数据,输出精准数字结果"
}
]
};
);
// STDIO标准传输启动服务
const transport = new StdioServerTransport();
await server.connect(transport);
console.log("✅ MCP Server 启动完成,等待客户端连接");
3.2 MCP客户端 src/client.ts
1.29.0 无 McpClient,仅原生 Client 可用,无模块缺失报错:
typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
async function runDemo() {
// 初始化客户端
const client = new Client({
name: "ts-mcp-client-demo",
version: "1.29.0"
});
// 连接本地编译后的服务端
const transport = new StdioClientTransport({
command: "node",
args: ["./dist/server.js"]
});
await client.connect(transport);
console.log("✅ 客户端连接MCP服务成功");
// 拉取全部可用工具
const { tools } = await client.listTools();
console.log("可用工具列表:", tools.map(item => item.name));
// 调用时间工具
const timeRes = await client.callTool({ name: "get-current-time", arguments: {} });
console.log("\n当前时间:", timeRes);
// 调用文本统计工具
const textRes = await client.callTool({
name: "count-text-length",
arguments: { text: "TypeScript开发MCP AI Agent" }
});
console.log("\n文本统计结果:", textRes);
// 读取业务资源上下文
const resourceRes = await client.readResource({ uri: "biz://agent-common-config" });
console.log("\n业务配置上下文:", resourceRes);
}
runDemo().catch(console.error);
3.3 编译运行
bash
# 编译TS代码至dist文件夹
npm run build
# 执行客户端测试全链路调用
npm start
四、集成 Claude Code(官方标准命令行方式)
4.1 核心说明
- 新版Claude Code 废弃独立mcp.json,不推荐手动修改settings.json;
- 统一使用
claude mcp add命令自动写入配置,规避JSON语法错误; - 两种挂载范围:
--scope user全局生效 / 默认local仅当前项目生效。
4.2 挂载自定义MCP服务
bash
# 全局挂载(所有项目均可调用该套工具,替换为你的dist/server.js绝对路径)
claude mcp add --scope user ts-custom-mcp-server -- node /Users/xxx/project/dist/server.js
4.3 配套运维命令
bash
# 查看所有已挂载MCP服务,校验是否注册成功
claude mcp list
# 查看指定服务详情
claude mcp inspect ts-custom-mcp-server
# 删除已挂载服务
claude mcp remove --scope user ts-custom-mcp-server
4.4 验证效果
重启Claude Code会话,输入自然语言指令:
帮我获取当前系统时间,并统计文本"MCP开发AI工具"的字数
模型会自动识别并调用我们注册的两个自定义工具。
五、集成 OpenAI Codex 大模型
Codex无原生MCP支持,通过MCP Client中转工具调用,实现模型决策+标准化工具执行:
5.1 安装依赖
bash
npm install openai
5.2 联动代码 src/codex-agent.ts
typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function codexMcpAgent() {
// 初始化MCP客户端
const mcpClient = new Client({ name: "codex-mcp-bridge", version: "1.29.0" });
const transport = new StdioClientTransport({
command: "node",
args: ["./dist/server.js"]
});
await mcpClient.connect(transport);
const { tools } = await mcpClient.listTools();
// Codex自动判断是否调用工具
const chatRes = await openai.chat.completions.create({
model: "code-davinci-002",
messages: [{ role: "user", content: "获取当前时间并统计文本「MCP Agent开发」字数" }],
tools: tools,
tool_choice: "auto"
});
const message = chatRes.choices[0].message;
if (message.tool_calls) {
for (const call of message.tool_calls) {
const result = await mcpClient.callTool({
name: call.function.name,
arguments: JSON.parse(call.function.arguments || "{}")
});
console.log("MCP工具执行输出:", result);
}
}
}
codexMcpAgent().catch(console.error);
六、打包发布私有NPM包(企业团队复用)
6.1 package.json 发包标准配置
json
{
"name": "@team/ts-mcp-server",
"version": "1.0.0",
"type": "module",
"main": "dist/server.js",
"types": "dist/server.d.ts",
"bin": {
"ts-mcp-server": "./dist/server.js"
},
"files": ["dist/**/*"],
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build",
"start": "node dist/server.js"
},
"dependencies": {
"@modelcontextprotocol/sdk": "1.29.0",
"zod": "^3.24.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"ts-node": "^10.9.0",
"typescript": "^5.5.0"
},
"private": true,
"description": "企业内部私有MCP工具服务,统一AI Agent能力",
"license": "MIT"
}
关键配置说明:
private: true:禁止公网发布,仅私有仓库可用;bin:安装后全局命令ts-mcp-server一键启动;prepublishOnly:发布前自动编译,保证dist文件最新。
6.2 完整发包流程(解决CNPM/OTP报错)
问题1:CNPM报错 Public registration is not allowed
淘宝镜像 registry.npmmirror.com 关闭公共注册,登录/发包必须切换官方源:
bash
# 切换官方NPM源
npm config set registry https://registry.npmjs.org/
# 校验源是否切换成功
npm config get registry
问题2:npm login invalid otp 验证码无效
- 开启设备自动同步时间,OTP基于时间校验,时差超30s直接失效;
- 关闭VPN/代理,避免时区错乱;
- 长期方案:使用永久Access Token替代验证码登录
bash
# 官网npmjs.com创建Classic Publish Token,登录时密码粘贴token
npm login --auth-type=legacy
发布步骤
bash
# 1. 编译代码
npm run build
# 2. 登录官方npm源
npm login
# 3. 发布私有包
npm publish
团队安装使用
bash
npm install @team/ts-mcp-server
# 全局命令启动MCP服务
ts-mcp-server
七、高频踩坑汇总
- TS2307 找不到 client/mcp.js
1.29.0版本客户端无McpClient,仅服务端支持McpServer,客户端统一使用原生Client; - TS2591 Buffer类型不存在
tsconfig新增"types": ["node"],确保安装@types/node; - TS5110 module配置不匹配
module、moduleResolution必须同时为NodeNext; - Claude MCP挂载失败
使用claude mcp add命令行挂载,路径必须填绝对路径; - CNPM无法登录发包
发包强制切换官方registry,日常安装包可切淘宝镜像加速; - invalid otp 验证码报错
同步系统时间,使用永久Publish Token绕过动态验证码。
八、适用业务场景
- 企业内部文档处理Agent:封装文件读取、摘要、格式转换工具;
- 业务智能问答:MCP Resources存储知识库,Tools调用业务接口;
- 多模型统一工具中台:一套MCP服务同时对接Claude、GPT、Codex;
- IDE本地AI插件:Claude Code挂载私有工具,实现自定义工程化能力。
九、总结
基于TypeScript+MCP 1.29.0搭建AI Agent工具层,是当前工程化最优方案:通过标准化协议解耦模型与业务逻辑,依托TS强类型降低线上异常,同时支持Claude Code本地接入、私有NPM包团队复用,适合企业规模化AI应用落地。