JS 服务器案例
本页面展示了一些MCP实际应用的案例,帮助您理解如何在不同场景中利用MCP扩展AI模型的能力。
1. 数据检索与分析助手
场景描述
创建一个能够访问和分析公司内部数据库的AI助手,使非技术人员能够通过自然语言查询获取数据洞察。
MCP实现
// 导入必要的依赖
import { Server, ToolError } from '@modelcontextprotocol/server';
import express from 'express';
import cors from 'cors';
import knex from 'knex';
// 初始化数据库连接
const db = knex({
client: 'pg',
connection: {
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD || 'password',
database: process.env.DB_NAME || 'company_data'
}
});
// 创建MCP服务器
const server = new Server({
name: 'data-assistant',
description: '公司内部数据访问与分析助手',
version: '1.0.0'
});
// 数据库查询工具
server.registerTool({
name: 'query_database',
description: '执行SQL查询并返回结果',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'SQL查询语句,仅支持SELECT操作'
}
},
required: ['query']
},
handler: async ({ query }) => {
// 安全检查 - 只允许SELECT查询
if (!query.trim().toLowerCase().startsWith('select')) {
throw new ToolError('只允许SELECT查询操作');
}
try {
// 执行查询
const results = await db.raw(query);
return {
data: results.rows,
rowCount: results.rowCount,
columns: results.fields ? results.fields.map(f => f.name) : []
};
} catch (error) {
throw new ToolError(`查询执行失败: ${error.message}`);
}
}
});
// 数据分析工具
server.registerTool({
name: 'analyze_data',
description: '分析数据集并返回结果',
parameters: {
type: 'object',
properties: {
data: {
type: 'array',
description: '要分析的数据集'
},
analysisType: {
type: 'string',
description: '分析类型: summary, trend, forecast',
enum: ['summary', 'trend', 'forecast']
}
},
required: ['data', 'analysisType']
},
handler: async ({ data, analysisType }) => {
// 数据验证
if (!Array.isArray(data) || data.length === 0) {
throw new ToolError('无效的数据集');
}
let analysis;
switch (analysisType) {
case 'summary':
analysis = computeSummaryStats(data);
break;
case 'trend':
analysis = identifyTrends(data);
break;
case 'forecast':
analysis = generateForecast(data);
break;
default:
throw new ToolError(`不支持的分析类型: ${analysisType}`);
}
return {
analysis,
metadata: {
dataPoints: data.length,
analysisType
}
};
}
});
// 数据分析辅助函数
function computeSummaryStats(data) {
// 这里是一个简化的实现,真实场景中应该使用统计库
const numericFields = {};
// 确定哪些字段是数值型的
Object.keys(data[0]).forEach(key => {
if (typeof data[0][key] === 'number') {
numericFields[key] = [];
}
});
// 收集所有数值型字段的值
data.forEach(item => {
Object.keys(numericFields).forEach(key => {
if (typeof item[key] === 'number') {
numericFields[key].push(item[key]);
}
});
});
// 计算每个数值型字段的统计数据
const stats = {};
Object.keys(numericFields).forEach(key => {
const values = numericFields[key];
const sum = values.reduce((a, b) => a + b, 0);
const avg = sum / values.length;
const sorted = [...values].sort((a, b) => a - b);
const min = sorted[0];
const max = sorted[sorted.length - 1];
const median = sorted[Math.floor(sorted.length / 2)];
stats[key] = { min, max, avg, median, sum };
});
return {
numericStats: stats,
totalRecords: data.length
};
}
function identifyTrends(data) {
// 简化的趋势分析实现
// 实际应用中应使用专门的时间序列分析库
return {
message: "趋势分析需要更复杂的实现,这里只是示例",
trendDetected: "上升/下降/持平", // 示例结果
confidence: 0.85 // 示例置信度
};
}
function generateForecast(data) {
// 简化的预测实现
// 实际应用中应使用专门的预测库
return {
message: "预测分析需要更复杂的实现,这里只是示例",
forecastValues: [101, 105, 110], // 示例预测值
confidenceInterval: [0.8, 0.9] // 示例置信区间
};
}
// 创建Express应用
const app = express();
app.use(cors());
app.use(express.json());
// 处理MCP请求
app.post('/mcp', async (req, res) => {
try {
const response = await server.handleRequest(req.body);
res.json(response);
} catch (error) {
console.error('处理MCP请求时出错:', error);
res.status(500).json({ error: '服务器内部错误' });
}
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`数据分析MCP服务器运行在端口 ${PORT}`);
});
用户体验
用户可以提问如:
- "查询过去6个月销售额最高的5个产品"
- "分析上个季度客户反馈中的主要趋势"
- "预测下个月的网站流量"
AI会使用MCP工具执行必要的数据库查询和分析,然后以易于理解的方式呈现结果。
2. 实时天气和新闻集成
场景描述
为AI模型提供访问实时天气数据和新闻的能力,使其能够在回答中融入当前信息。
MCP实现
import { Server } from '@modelcontextprotocol/server';
import express from 'express';
import cors from 'cors';
import axios from 'axios';
// 创建MCP服务器
const server = new Server({
name: 'real-time-info',
description: '实时天气和新闻信息服务',
version: '1.0.0'
});
// 获取天气信息工具
server.registerTool({
name: 'get_weather',
description: '获取指定位置的天气信息',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: '位置名称,如"北京"或"上海"'
}
},
required: ['location']
},
handler: async ({ location }) => {
try {
// 使用天气API
const weatherApiKey = process.env.WEATHER_API_KEY || 'your_api_key';
const response = await axios.get(
`https://api.weatherapi.com/v1/forecast.json?key=${weatherApiKey}&q=${encodeURIComponent(location)}&days=3&aqi=no&alerts=yes`
);
const weatherData = response.data;
return {
current: {
temperature: weatherData.current.temp_c,
condition: weatherData.current.condition.text,
humidity: weatherData.current.humidity,
windSpeed: weatherData.current.wind_kph
},
forecast: weatherData.forecast.forecastday.map(day => ({
date: day.date,
maxTemp: day.day.maxtemp_c,
minTemp: day.day.mintemp_c,
condition: day.day.condition.text,
chanceOfRain: day.day.daily_chance_of_rain
}))
};
} catch (error) {
console.error('获取天气数据失败:', error);
throw new Error(`无法获取天气数据: ${error.message}`);
}
}
});
// 获取新闻信息工具
server.registerTool({
name: 'get_news',
description: '获取指定主题的最新新闻',
parameters: {
type: 'object',
properties: {
topic: {
type: 'string',
description: '新闻主题,如"科技"或"体育"'
},
count: {
type: 'number',
description: '返回的新闻数量'
}
},
required: ['topic']
},
handler: async ({ topic, count = 5 }) => {
try {
// 使用新闻API
const newsApiKey = process.env.NEWS_API_KEY || 'your_api_key';
const response = await axios.get(
`https://newsapi.org/v2/everything?q=${encodeURIComponent(topic)}&apiKey=${newsApiKey}&pageSize=${count}&language=zh`
);
const newsData = response.data;
return {
articles: newsData.articles.map(article => ({
title: article.title,
source: article.source.name,
url: article.url,
publishedAt: article.publishedAt,
description: article.description
}))
};
} catch (error) {
console.error('获取新闻数据失败:', error);
throw new Error(`无法获取新闻数据: ${error.message}`);
}
}
});
// 注册天气和新闻的提示模板
server.registerPrompt({
name: 'weather_inquiry',
description: '询问天气信息',
template: `
我想了解以下地点的天气情况:
地点:[输入城市名称]
请告诉我当前天气状况以及未来几天的预报。
`
});
server.registerPrompt({
name: 'news_inquiry',
description: '询问最新新闻',
template: `
我想了解关于以下主题的最新新闻:
主题:[输入感兴趣的主题]
数量:[可选,希望获取的新闻数量]
请提供相关新闻的标题、来源和简短描述。
`
});
// 创建Express应用
const app = express();
app.use(cors());
app.use(express.json());
// 处理MCP请求
app.post('/mcp', async (req, res) => {
try {
const response = await server.handleRequest(req.body);
res.json(response);
} catch (error) {
console.error('处理MCP请求时出错:', error);
res.status(500).json({ error: '服务器内部错误' });
}
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`实时信息MCP服务器运行在端口 ${PORT}`);
});
用户体验
用户可以获取最新信息,如:
- "今天北京天气怎么样?我应该带伞吗?"
- "告诉我最近的科技新闻头条"
- "上海未来三天的天气预报"
AI会使用MCP工具获取实时信息,然后融入到回答中,提供准确的最新数据。