npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nicekit/mcp

v1.1.0

Published

NiceMCP - 基于 MCP 协议的领域服务组件,调用 nicekit 能力为 Agent 提供各领域服务

Readme

@nicekit/mcp - NiceMCP 组件服务

基于 MCP 协议的领域服务组件,调用 nicekit 能力为 Agent 提供各领域服务。

概述

NiceMCP 是一个企业级的 MCP (Model Context Protocol) 服务组件,它:

  • 集成 NiceKit 能力:复用 nicekit 的配置管理、错误处理、JSON 输出、参数验证和环境变量等功能
  • 提供领域服务:为 AI Agent 提供财富运势、健康分析、数据分析、通用工具等多领域服务
  • 标准化协议:基于 MCP 协议,与 AI 模型无缝集成
  • 模块化设计:易于扩展新的领域服务

特性

核心能力

  • 配置管理:多层配置查找链,支持环境变量、配置文件、默认值
  • 错误处理:场景化错误恢复建议,结构化 JSON 错误输出
  • JSON 输出:Schema 版本化,支持多种输出格式
  • 参数验证:数值范围约束,枚举值验证,安全解析函数
  • 环境变量:30+ 预定义环境变量,类型安全解析

领域服务

  • 🏦 财富运势服务:每日运势、投资建议、财务规划、财富分析
  • 💪 健康分析服务:健康数据分析、BMI计算、运动计划、营养指导、心理健康
  • 📊 数据分析服务:数据统计、相关性分析、时间序列分析、可视化建议
  • 🔧 工具服务:文本处理、格式转换、编码解码、哈希生成、UUID生成、密码生成

架构特性

  • 🚀 高性能:异步处理,支持并发请求
  • 🔒 安全可靠:参数验证,错误恢复,输入清理
  • 📈 可扩展:插件化架构,易于添加新领域服务
  • 📝 完整文档:详细的API文档和使用示例

快速开始

安装

npm install @nicekit/mcp

基础使用

import {
  NiceMcpService,
  FortuneService,
  HealthService,
  DataService,
  ToolService
} from '@nicekit/mcp';

// 1. 创建服务
const mcpService = new NiceMcpService({
  port: 3000,
  host: 'localhost',
  auth: { type: 'none' },
  logging: { level: 'info', console: true }
});

// 2. 注册领域服务
const nicekit = mcpService.getNiceKit();

mcpService.registerService('fortune', new FortuneService(nicekit));
mcpService.registerService('health', new HealthService(nicekit));
mcpService.registerService('data', new DataService(nicekit));
mcpService.registerService('tool', new ToolService(nicekit));

// 3. 启动服务
await mcpService.start();

// 4. 处理 Agent 请求
const request = {
  jsonrpc: '2.0',
  method: 'fortune/get_daily_fortune',
  params: {
    arguments: {
      zodiac: '白羊座',
      date: '2026-06-21'
    }
  },
  id: 1
};

const response = await mcpService.handleRequest(request);
console.log(response);

// 5. 停止服务
await mcpService.stop();

领域服务详解

1. 财富运势服务 (FortuneService)

提供财富运势分析、投资建议、财务规划等服务。

可用工具

| 工具名称 | 描述 | 必填参数 | |---------|------|---------| | get_daily_fortune | 获取每日财富运势 | zodiac | | analyze_investment | 投资分析建议 | amount, risk_level | | financial_planning | 财务规划建议 | monthly_income, monthly_expense | | wealth_analysis | 财富状况分析 | total_assets, total_debt, annual_income |

使用示例

// 获取白羊座今日运势
const fortuneRequest = {
  jsonrpc: '2.0',
  method: 'fortune/get_daily_fortune',
  params: {
    arguments: {
      zodiac: '白羊座',
      date: '2026-06-21'
    }
  },
  id: 1
};

// 投资分析
const investmentRequest = {
  jsonrpc: '2.0',
  method: 'fortune/analyze_investment',
  params: {
    arguments: {
      amount: 100000,
      risk_level: 'medium',
      investment_type: '基金'
    }
  },
  id: 2
};

2. 健康分析服务 (HealthService)

提供健康数据分析、运动建议、营养指导、心理健康等服务。

可用工具

| 工具名称 | 描述 | 必填参数 | |---------|------|---------| | analyze_health_data | 分析健康数据 | height, weight, age, gender | | calculate_bmi | 计算BMI指数 | height, weight | | generate_exercise_plan | 生成运动计划 | fitness_level, goal | | nutrition_guidance | 营养指导 | age, gender, weight, height, activity_level | | mental_health_assessment | 心理健康评估 | stress_level, sleep_quality, mood | | sleep_analysis | 睡眠分析 | average_sleep_hours |

使用示例

// 健康数据分析
const healthRequest = {
  jsonrpc: '2.0',
  method: 'health/analyze_health_data',
  params: {
    arguments: {
      height: 175,
      weight: 70,
      age: 30,
      gender: 'male',
      blood_pressure_systolic: 120,
      blood_pressure_diastolic: 80,
      heart_rate: 72,
      blood_sugar: 5.5
    }
  },
  id: 1
};

// 生成运动计划
const exerciseRequest = {
  jsonrpc: '2.0',
  method: 'health/generate_exercise_plan',
  params: {
    arguments: {
      fitness_level: 'intermediate',
      goal: 'weight_loss',
      available_time: 60,
      equipment: 'basic'
    }
  },
  id: 2
};

3. 数据分析服务 (DataService)

提供数据分析、统计、可视化建议、数据清洗等服务。

可用工具

| 工具名称 | 描述 | 必填参数 | |---------|------|---------| | analyze_dataset | 分析数据集 | data | | calculate_statistics | 计算统计指标 | data | | suggest_visualization | 推荐可视化方式 | data_type, purpose | | clean_data | 数据清洗建议 | data | | correlation_analysis | 相关性分析 | data, columns | | time_series_analysis | 时间序列分析 | data, time_column, value_column |

使用示例

// 计算统计指标
const statsRequest = {
  jsonrpc: '2.0',
  method: 'data/calculate_statistics',
  params: {
    arguments: {
      data: JSON.stringify([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
      metrics: 'mean,median,std,min,max'
    }
  },
  id: 1
};

// 相关性分析
const correlationRequest = {
  jsonrpc: '2.0',
  method: 'data/correlation_analysis',
  params: {
    arguments: {
      data: JSON.stringify([
        { x: 1, y: 2 },
        { x: 2, y: 4 },
        { x: 3, y: 6 }
      ]),
      columns: JSON.stringify(['x', 'y']),
      method: 'pearson'
    }
  },
  id: 2
};

4. 工具服务 (ToolService)

提供通用工具服务,如文本处理、格式转换、编码解码等。

可用工具

| 工具名称 | 描述 | 必填参数 | |---------|------|---------| | text_process | 文本处理 | text, operation | | format_convert | 格式转换 | data, from_format, to_format | | encode_decode | 编码解码 | data, operation, encoding | | hash_generate | 哈希生成 | data, algorithm | | uuid_generate | UUID生成 | - | | password_generate | 密码生成 | - |

使用示例

// 文本处理
const textRequest = {
  jsonrpc: '2.0',
  method: 'tool/text_process',
  params: {
    arguments: {
      text: 'Hello, World!',
      operation: 'uppercase'
    }
  },
  id: 1
};

// 格式转换
const convertRequest = {
  jsonrpc: '2.0',
  method: 'tool/format_convert',
  params: {
    arguments: {
      data: JSON.stringify({ name: 'test', value: 123 }),
      from_format: 'json',
      to_format: 'csv'
    }
  },
  id: 2
};

// 生成UUID
const uuidRequest = {
  jsonrpc: '2.0',
  method: 'tool/uuid_generate',
  params: {
    arguments: {
      version: 4,
      count: 5,
      format: 'standard'
    }
  },
  id: 3
};

配置管理

配置文件

NiceMCP 支持多层配置查找链:

  1. 显式路径:通过 --config 参数指定
  2. 环境变量NICECLI_CONFIG 环境变量
  3. 当前目录nicecli.json.nicecli.json
  4. 用户目录~/.nicecli.json~/.config/nicecli/config.json

配置示例

{
  "port": 3000,
  "host": "localhost",
  "auth": {
    "type": "api_key",
    "apiKey": "your-api-key"
  },
  "logging": {
    "level": "info",
    "console": true
  },
  "performance": {
    "timeout": 30000,
    "maxConcurrent": 100
  }
}

环境变量

NiceMCP 支持 30+ 预定义环境变量:

# 配置文件
NICECLI_CONFIG=/path/to/config.json

# 服务配置
NICECLI_PORT=3000
NICECLI_HOST=localhost

# 认证配置
NICECLI_AUTH_TYPE=api_key
NICECLI_AUTH_API_KEY=your-api-key

# 日志配置
NICECLI_LOG_LEVEL=info
NICECLI_LOG_CONSOLE=true

# 性能配置
NICECLI_TIMEOUT=30000
NICECLI_MAX_CONCURRENT=100

错误处理

NiceMCP 提供完善的错误处理机制:

错误类型

| 错误代码 | 描述 | 恢复建议 | |---------|------|---------| | CONFIG_NOT_FOUND | 配置文件未找到 | nicecli config init | | CONFIG_INVALID | 配置无效 | nicecli config validate | | CONNECTION_FAILED | 连接失败 | nicecli connect | | AUTH_FAILED | 认证失败 | nicecli auth login | | INVALID_INPUT | 输入无效 | nicecli help | | EXECUTION_FAILED | 执行失败 | nicecli retry |

错误响应格式

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "参数验证失败",
    "data": {
      "code": "INVALID_ARGUMENT",
      "message": "缺少必填参数: zodiac",
      "recoveryHints": [
        {
          "command": "nicecli help",
          "description": "查看帮助信息"
        }
      ]
    }
  },
  "id": 1
}

NiceKit 集成

NiceMCP 深度集成 NiceKit 的核心能力:

配置管理

import { NiceKitIntegration } from '@nicekit/mcp';

const nicekit = new NiceKitIntegration();

// 加载配置
const config = await nicekit.loadConfig();

// 获取配置值
const timeout = nicekit.getConfig('timeout', 30);

// 验证配置
const validation = nicekit.validateConfig(config);

错误处理

// 创建错误
const error = nicekit.createError('TEST_ERROR', '测试错误', {
  details: '错误详情'
});

// 格式化错误
const jsonError = nicekit.formatErrorJson(error);
const textError = nicekit.formatErrorText(error);

参数验证

// 验证值
const result = nicekit.validateValue(0.7, [
  nicekit.createRangeRule(0, 2, 'temperature')
]);

// 创建验证规则
const rangeRule = nicekit.createRangeRule(0, 100, 'percentage');
const enumRule = nicekit.createEnumRule(['low', 'medium', 'high'], 'risk_level');

环境变量

// 获取环境变量
const model = nicekit.getEnv('NICECLI_MODEL', 'default-model');

// 设置环境变量
nicekit.setEnv('NICECLI_DEBUG', 'true');

// 检查环境变量
if (nicekit.hasEnv('NICECLI_API_KEY')) {
  console.log('API Key 已设置');
}

自定义领域服务

创建自定义服务

import { DomainServiceBase } from '@nicekit/mcp';
import { ToolDefinition, McpRequest, McpResponse } from '@nicekit/mcp';

export class CustomService extends DomainServiceBase {
  readonly name = 'custom';
  readonly description = '自定义服务';
  
  readonly tools: ToolDefinition[] = [
    this.createToolDefinition(
      'custom_tool',
      '自定义工具',
      {
        param1: { type: 'string', description: '参数1' },
        param2: { type: 'number', description: '参数2' }
      },
      ['param1']
    )
  ];

  protected async onInitialize(): Promise<void> {
    this.log('info', '自定义服务初始化完成');
  }

  protected async onDestroy(): Promise<void> {
    this.log('info', '自定义服务已销毁');
  }

  protected async executeTool(toolName: string, params: Record<string, any>): Promise<any> {
    switch (toolName) {
      case 'custom_tool':
        return await this.customTool(params);
      default:
        throw new Error(`未知工具: ${toolName}`);
    }
  }

  private async customTool(params: Record<string, any>): Promise<any> {
    const { param1, param2 } = params;
    
    // 实现自定义逻辑
    return {
      result: `处理结果: ${param1}, ${param2}`,
      timestamp: new Date().toISOString()
    };
  }
}

注册自定义服务

import { NiceMcpService, NiceKitIntegration } from '@nicekit/mcp';
import { CustomService } from './custom-service';

const mcpService = new NiceMcpService();
const nicekit = mcpService.getNiceKit();

// 注册自定义服务
mcpService.registerService('custom', new CustomService(nicekit));

// 启动服务
await mcpService.start();

性能优化

并发控制

const mcpService = new NiceMcpService({
  performance: {
    maxConcurrent: 50, // 最大并发数
    timeout: 30000     // 请求超时时间
  }
});

缓存配置

const mcpService = new NiceMcpService({
  performance: {
    cache: true,
    cacheTtl: 300 // 缓存过期时间(秒)
  }
});

监控和日志

系统状态

const status = mcpService.getSystemStatus();
console.log('系统状态:', status);

// 输出示例
{
  version: '1.0.0',
  uptime: 3600000,
  services: [
    {
      name: 'fortune',
      status: 'running',
      requestCount: 100,
      errorCount: 2,
      avgResponseTime: 50
    }
  ],
  resources: {
    cpu: 45.2,
    memory: 128.5,
    disk: 1024
  },
  timestamp: '2026-06-21T10:00:00.000Z'
}

日志配置

const mcpService = new NiceMcpService({
  logging: {
    level: 'info',      // debug, info, warn, error
    console: true,      // 输出到控制台
    file: '/var/log/nicemcp.log', // 输出到文件
    json: true          // JSON 格式
  }
});

安全性

认证配置

// API Key 认证
const mcpService = new NiceMcpService({
  auth: {
    type: 'api_key',
    apiKey: 'your-secret-key'
  }
});

// JWT 认证
const mcpService = new NiceMcpService({
  auth: {
    type: 'jwt',
    jwtSecret: 'your-jwt-secret'
  }
});

输入验证

NiceMCP 自动验证所有输入参数:

  • 必填参数检查
  • 参数类型验证
  • 数值范围约束
  • 枚举值验证

错误恢复

每个错误都包含恢复建议,帮助用户快速解决问题。

最佳实践

1. 服务配置

// 推荐配置
const mcpService = new NiceMcpService({
  port: 3000,
  host: 'localhost',
  auth: { type: 'api_key', apiKey: process.env.API_KEY },
  logging: { level: 'info', console: true },
  performance: { timeout: 30000, maxConcurrent: 100 }
});

2. 错误处理

try {
  const response = await mcpService.handleRequest(request);
  if (response.error) {
    console.error('请求失败:', response.error);
    // 处理错误
  }
} catch (error) {
  console.error('服务错误:', error);
  // 重启服务或记录日志
}

3. 性能监控

// 定期检查系统状态
setInterval(() => {
  const status = mcpService.getSystemStatus();
  if (status.services.some(s => s.errorCount > 100)) {
    console.warn('错误率过高,需要检查服务');
  }
}, 60000);

4. 资源管理

// 优雅关闭
process.on('SIGTERM', async () => {
  console.log('收到关闭信号,正在停止服务...');
  await mcpService.stop();
  process.exit(0);
});

示例代码

完整示例

import {
  NiceMcpService,
  FortuneService,
  HealthService,
  DataService,
  ToolService
} from '@nicekit/mcp';

async function main() {
  // 创建服务
  const mcpService = new NiceMcpService({
    port: 3000,
    logging: { level: 'info', console: true }
  });

  // 注册服务
  const nicekit = mcpService.getNiceKit();
  mcpService.registerService('fortune', new FortuneService(nicekit));
  mcpService.registerService('health', new HealthService(nicekit));
  mcpService.registerService('data', new DataService(nicekit));
  mcpService.registerService('tool', new ToolService(nicekit));

  // 启动服务
  await mcpService.start();
  console.log('NiceMCP 服务已启动');

  // 处理请求
  const request = {
    jsonrpc: '2.0',
    method: 'fortune/get_daily_fortune',
    params: { arguments: { zodiac: '白羊座' } },
    id: 1
  };

  const response = await mcpService.handleRequest(request);
  console.log('响应:', response);

  // 停止服务
  await mcpService.stop();
}

main().catch(console.error);

故障排除

常见问题

  1. 服务启动失败

    • 检查端口是否被占用
    • 检查配置文件是否正确
    • 查看日志获取详细错误信息
  2. 请求超时

    • 增加超时时间配置
    • 检查网络连接
    • 减少并发请求数量
  3. 参数验证失败

    • 检查必填参数是否完整
    • 验证参数类型是否正确
    • 查看错误响应中的详细信息
  4. 认证失败

    • 检查 API Key 是否正确
    • 验证认证配置
    • 检查环境变量设置

调试模式

const mcpService = new NiceMcpService({
  logging: { level: 'debug', console: true }
});

更新日志

v1.0.0

  • 初始版本发布
  • 支持财富运势、健康分析、数据分析、工具服务
  • 集成 NiceKit 核心能力
  • 完整的错误处理和参数验证

许可证

MIT License

贡献

欢迎贡献代码和提出建议!

联系方式

  • 项目主页:https://github.com/nicekit/mcp
  • 文档:https://nicekit.github.io/mcp
  • 问题反馈:https://github.com/nicekit/mcp/issues