MCP 无服务器实现

MCP 无服务器实现

用于模型上下文协议 (MCP) 的无服务器实现,支持工具管理的简洁接口。

快速入门

安装

使用 npm 安装:

npm install @tilfin/mcp-serverless

使用

  1. 创建并注册工具:
    import { createService, ToolManager } from '@tilfin/mcp-serverless';
    
    const toolManager = new ToolManager();
    toolManager.registerTools([
      {
        name: 'calculator',
        description: '执行基本算术运算',
        inputSchema: {
          type: 'object',
          properties: {
            operation: { type: 'string' },
            numbers: { type: 'array', items: { type: 'number' } }
          },
          required: ['operation', 'numbers']
        },
        toolFunction: async (params, ctx) => {
          if (ctx.apiKey !== 'xyz') throw new Error('无效的 API 密钥');
          let result;
          if (params.operation === 'add') {
            result = params.numbers.reduce((sum, n) => sum + n, 0);
          }
          return { result };
        }
      }
    ]);
    
  2. 创建服务客户端并调用工具:
    const client = createService(toolManager);
    const toolsList = await client.listTools();
    const result = await client.callTool({
      name: 'calculator',
      arguments: {
        operation: 'add',
        numbers: [1, 2, 3]
      },
      ctx: { apiKey: 'xyz' }
    });
    

更多示例和 API 参考,请查看 README。