工具管理无服务器实现

MCP Serverless 是一个基于 Model Context Protocol (MCP) 架构的无服务器实现,提供工具注册、管理和请求处理功能,适用于需要灵活工具管理的开发场景。

  • by tilfin
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 tilfin/mcp-serverless

使用说明

MCP无服务器

模型上下文协议(MCP)架构的无服务器实现,通过干净的界面实现工具管理。

概述

此软件包提供了MCP服务器的无服务器实现,允许您:

  • 注册和管理工具
  • 处理与工具相关的请求
  • 创建内存中的客户端-服务器连接
  • 使用上下文扩展请求,以启用来自客户端的凭据传输

安装

npm install @tilfin/mcp-serverless

用法

工具注册并为服务实现创建客户端

import { createService, ToolManager } from '@tilfin/mcp-serverless';

// Create a tool manager
const toolManager = new ToolManager();

// Register tools
toolManager.registerTools([
  {
    name: 'calculator',
    description: 'Performs basic arithmetic operations',
    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('Invalid API Key');

      let result;
      if (params.operation === 'add') {
        result = params.numbers.reduce((sum, n) => sum + n, 0);
      }
      return { result };
    }
  }
]);

// Create a serverless client
const client = createService(toolManager);

// List available tools
const toolsList = await client.listTools();

// Call a tool
try {
  const result = await client.callTool({
    name: 'calculator',
    arguments: {
      operation: 'add',
      numbers: [1, 2, 3]
    }
  });
} catch (err) {
  // raise Invalid API Key error
}

// Call a tool with context
const result = await client.callTool({
  name: 'calculator',
  arguments: {
    operation: 'add',
    numbers: [1, 2, 3]
  },
  ctx: { apiKey: 'xyz' }
});

api参考

ToolManager 类

管理工具的注册和处理。

Tool 接口

工具必须实现以下接口:

interface Tool {
  name: string;
  description: string;
  inputSchema: ToolInput;
  toolFunction: (args: CallToolRequestArguments, ctx: CallToolRequestContext) => Promise<CallToolResultContent>;
}

createServer(serverInfo, toolManager)

使用给定的工具管理器创建MCP服务器。

createService(toolManager)

为无服务器操作创建内存中的客户端-服务器设置。

例子

标准I/O传输

该包包括使用stdio传输进行客户端和服务器通信的示例:

  • StdioClientTransport:允许客户端通过标准输入/输出与服务器通信
  • StdioServerTransport:使服务器能够通过标准输入/输出处理请求

查看示例实现: