-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
90 lines (80 loc) · 2.68 KB
/
Copy pathindex.ts
File metadata and controls
90 lines (80 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { Logger } from '@aws-lambda-powertools/logger';
import { McpServer } from '@modelcontextprotocol/server';
import { handle } from 'hono/aws-lambda';
import { z } from 'zod';
import { createHonoApp } from 'aws-lambda-mcp-server';
const logger = new Logger();
const createMcpServer = () => {
const server = new McpServer({
name: 'hello-server',
version: '1.0.0',
},
);
server.registerTool(
'say_hello',
{
description: 'Greets the user with a friendly message.',
inputSchema: z.object({ who: z.string() }),
},
async ({ who }: { who: string }) => ({
content: [{
type: 'text',
text: `${who} さん、こんにちは!`,
}],
}),
);
return server;
};
const app = createHonoApp(createMcpServer, {
host: '0.0.0.0',
});
// Lambda handler
export const handler = handle(app);
// 以下、ローカルサーバー向けコード
if (!process.env.AWS_LAMBDA_FUNCTION_NAME) {
const main = async () => {
const { z } = await import('zod');
// 0 と well-known ポートはこのアプリの仕様として許可しない
const portSchema = z.coerce.number().int().min(1024).max(65535).default(8080);
const parsePort = (value: string | undefined): number => {
const result = portSchema.safeParse(value);
if (!result.success) {
logger.warn(`無効または要件で許可されていないポート値: ${result.error.issues[0].message} (デフォルト: 8080に設定)`);
return 8080;
}
return result.data;
};
const { serve } = await import('@hono/node-server');
const port = parsePort(process.env.PORT);
try {
const server = serve({
fetch: app.fetch,
port,
}, (info) => {
logger.info(`MCP サーバーがポート ${info.port} でリッスン中`);
});
// Graceful shutdown
const shutdown = () => {
logger.info('サーバーをシャットダウンしています...');
const shutdownTimeout = setTimeout(() => {
logger.warn('シャットダウンがタイムアウトしました。強制終了します。');
process.exit(1);
}, 5000); // 5秒のタイムアウト
server.close(() => {
clearTimeout(shutdownTimeout);
logger.info('サーバーが正常にシャットダウンされました');
process.exit(0);
});
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
} catch (error) {
logger.error('サーバーのセットアップに失敗しました:', { error });
process.exit(1);
}
};
main().catch((err) => {
logger.error('error', { error: err });
process.exit(1);
});
}