AI服务器构建模板

一个用于创建模型上下文协议(MCP)服务器的实用模板,使AI助手能够与您的数据和服务进行交互。

  • by kbhuw
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 rhit-bhuwalk/MCP_TEMPLATE

使用说明

MCP模板-构建自己的AI服务器

创建模型上下文协议(MCP)服务器的实用模板,使AI助手能够与您的数据和服务进行交互。

概述

该模板为构建MCP服务器提供了基础,MCP服务器是人工智能助手可以连接的专门服务,用于访问外部数据、执行操作,并将其功能扩展到训练数据之外。

关键能力:

  • 将数据作为可查询资源公开
  • 为AI助手提供自定义工具以供执行
  • 处理实时数据操作(CRUD)
  • 连接多个数据源和服务

先决条件

  • Node.js 18+和npm
  • TypeScript知识
  • 了解REST API或类似概念

快速开始

git clone https://github.com/rhit-bhuwalk/MCP_TEMPLATE.git
cd MCP_TEMPLATE
npm install
npm run build
npm start

这将启动一个服务器,其中包含演示核心MCP功能的示例用户数据。

核心概念

资源

资源表示AI助手可以查询的数据集合。将它们视为返回结构化数据的API端点。

// Register a resource
dataService.registerResource('users', 'User account information');

// AI can now query: "Show me all users" or "Find user with ID 123"

工具

工具是AI助手可以执行的功能,用于对您的数据执行特定操作。

// Register a tool
server.registerTool(
  'create_user',
  'Create a new user account',
  z.object({
    name: z.string(),
    email: z.string().email()
  }),
  async (args) => {
    return await dataService.create('mcp://users', args);
  }
);

实施指南

1.定义您的数据结构

首先定义数据的形状:

interface Product {
  id: string;
  name: string;
  price: number;
  category: string;
  inStock: boolean;
}

2.注册资源

让AI助手发现您的数据:

// In your server setup
dataService.registerResource('products', 'Product inventory data');

// Seed with sample data
const sampleProducts: Product[] = [
  { id: '1', name: 'Laptop', price: 999, category: 'Electronics', inStock: true },
  { id: '2', name: 'Coffee Mug', price: 15, category: 'Kitchen', inStock: false }
];

dataService.seedData('mcp://products', sampleProducts);

3.添加自定义工具

为您的用例创建特定操作:

// Inventory management tool
server.registerTool(
  'update_stock_status',
  'Update product stock availability',
  z.object({
    productId: z.string(),
    inStock: z.boolean()
  }),
  async (args) => {
    const result = await dataService.update(
      'mcp://products', 
      args.productId, 
      { inStock: args.inStock }
    );
    return { success: true, product: result };
  }
);

// Analytics tool
server.registerTool(
  'get_category_summary',
  'Get inventory summary by category',
  z.object({
    category: z.string().optional()
  }),
  async (args) => {
    const products = await dataService.queryResource('mcp://products', {
      filter: args.category ? { category: args.category } : undefined
    });
    
    return {
      totalProducts: products.length,
      inStock: products.filter(p => p.inStock).length,
      outOfStock: products.filter(p => !p.inStock).length,
      averagePrice: products.reduce((sum, p) => sum + p.price, 0) / products.length
    };
  }
);

4.连接真实数据源

用实际数据替换内存存储:

// Example: Connect to a database
class DatabaseDataService extends DataService {
  async queryResource(uri: string, query?: any) {
    const resourceType = uri.split('://')[1];
    
    switch (resourceType) {
      case 'products':
        return await this.db.products.findMany({
          where: query?.filter || {}
        });
      case 'orders':
        return await this.db.orders.findMany({
          include: { items: true }
        });
      default:
        throw new Error(`Unknown resource: ${resourceType}`);
    }
  }
}

项目结构

src/
├── core/           # Core MCP server functionality
├── services/       # Data service implementations  
├── examples/       # Example implementations
│   └── server.ts   # Complete working example
└── index.ts        # Main entry point

从这里开始: src/examples/server.ts 包含一个完整的实现,显示了实践中的所有概念。

高级模式

多资源操作

server.registerTool(
  'process_order',
  'Process customer order and update inventory',
  z.object({
    customerId: z.string(),
    productIds: z.array(z.string())
  }),
  async (args) => {
    // Check inventory
    const products = await dataService.queryByIds('mcp://products', args.productIds);
    
    // Create order
    const order = await dataService.create('mcp://orders', {
      customerId: args.customerId,
      items: products,
      total: products.reduce((sum, p) => sum + p.price, 0)
    });
    
    // Update inventory
    for (const product of products) {
      await dataService.update('mcp://products', product.id, { 
        inStock: false 
      });
    }
    
    return { orderId: order.id, total: order.total };
  }
);

错误处理和验证

server.registerTool(
  'safe_user_operation',
  'Safely perform user operations with validation',
  schema,
  async (args) => {
    try {
      // Validate business rules
      if (args.email && !isValidEmail(args.email)) {
        throw new Error('Invalid email format');
      }
      
      const result = await dataService.performOperation(args);
      return { success: true, data: result };
      
    } catch (error) {
      return { 
        success: false, 
        error: error.message,
        code: 'VALIDATION_ERROR'
      };
    }
  }
);

测试您的服务器

# Run tests
npm test

# Test with a real AI assistant
npm start
# Connect Claude Desktop or other MCP-compatible client

部署考虑

  • 认证:添加API密钥或OAuth以供生产使用
  • 速率限制:针对高流量场景实施请求限制
  • 数据验证:始终验证来自AI助手的输入
  • 日志记录:添加用于调试和监控的全面日志记录
  • 错误处理:提供清晰的错误信息,帮助人工智能助手了解出了什么问题

后续步骤

  1. 检查示例 -通过学习了解模式 src/examples/server.ts
  2. 调整数据模型 -用域对象替换示例数据
  3. 添加特定于域的工具 -创建与您的业务逻辑相匹配的操作
  4. 连接真实数据源 -与数据库、API或文件系统集成
  5. 使用AI助手进行测试 -使用Claude、ChatGPT或其他MCP客户端验证功能

此模板提供了脚手架——您的领域专业知识和数据使其具有价值。