Repository navigation
Expand file tree
/
Copy pathregistry.ts
More file actions
303 lines (270 loc) · 8.31 KB
/
Copy pathregistry.ts
File metadata and controls
303 lines (270 loc) · 8.31 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
2
8000
45
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
* 서비스 레지스트리
*
* 서비스 프로바이더를 등록하고 MCP 서버에 도구를 연결합니다.
*/
import { diagnosticEvent } from '../utils/diagnostics.js';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { ServiceProvider, ServiceFactory } from './interfaces.js';
import type { ServiceInfo, ToolRegistration } from './types.js';
import { getErrorMessage, ServiceError, toServiceErrorDiagnostics } from './errors.js';
import { createToolOutputSchema } from './outputSchema.js';
function parseJsonText(text: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(text) as unknown;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
return null;
}
return null;
}
function firstString(...values: unknown[]): string | null {
for (const value of values) {
if (typeof value === 'string' && value.trim().length > 0) {
return value.trim();
}
}
return null;
}
function firstNumber(...values: unknown[]): number | null {
for (const value of values) {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string') {
const parsed = Number.parseFloat(value.replace(/km$/i, ''));
if (Number.isFinite(parsed)) {
return value.trim().toLowerCase().endsWith('km') ? Math.round(parsed * 1000) : parsed;
}
}
}
return null;
}
function normalizeProducts(products: unknown[]): Array<Record<string, unknown>> {
return products
.filter(
(item): item is Record<string, unknown> =>
Boolean(item) && typeof item === 'object' && !Array.isArray(item),
)
.map((item) => ({
code: firstString(item.itemCode, item.productCode, item.pluCd, item.id, item.productNo),
name: firstString(
item.itemName,
item.shortItemName,
item.goodsName,
item.productName,
item.movieName,
item.name,
),
price: firstNumber(
item.viewPrice,
item.salePrice,
item.sellPrice,
item.price,
item.originPrice,
item.searchItemSellPrice,
),
imageUrl: firstString(item.imageUrl),
raw: item,
}));
}
function normalizeStores(stores: unknown[]): Array<Record<string, unknown>> {
return stores
.filter(
(item): item is Record<string, unknown> =>
Boolean(item) && typeof item === 'object' && !Array.isArray(item),
)
.map((item) => ({
code: firstString(item.storeCode, item.code, item.id),
name: firstString(item.storeName, item.name, item.theaterName),
address: firstString(item.address, item.storeAddress),
distanceMeters: firstNumber(item.distanceM, item.distanceMeters, item.distance),
raw: item,
}));
}
function withStandardCollections(payload: Record<string, unknown>): Record<string, unknown> {
const standard: Record<string, unknown> = {};
if (Array.isArray(payload.products)) {
standard.products = normalizeProducts(payload.products);
}
if (Array.isArray(payload.stores)) {
standard.stores = normalizeStores(payload.stores);
}
if (Array.isArray(payload.places)) {
standard.places = normalizeStores(payload.places);
}
if (Array.isArray(payload.theaters)) {
standard.theaters = normalizeStores(payload.theaters);
}
if (Array.isArray(payload.movies)) {
standard.movies = normalizeProducts(payload.movies);
}
if (Object.keys(standard).length === 0) {
return payload;
}
return {
...payload,
standard,
};
}
function buildStructuredContent(result: {
content: Array<{ text: string }>;
structuredContent?: Record<string, unknown>;
}) {
if (result.structuredContent) {
return withStandardCollections(result.structuredContent);
}
const text = result.content[0]?.text || '';
const parsed = parseJsonText(text);
if (parsed) {
return withStandardCollections(parsed);
}
return { text };
}
/**
* 서비스 레지스트리 클래스
*
* 여러 서비스 프로바이더를 관리하고 MCP 서버에 등록합니다.
*
* @example
* ```typescript
* const registry = new ServiceRegistry();
* registry.register(createDaisoService);
* registry.register(createCuService);
* await registry.applyToServer(mcpServer);
* ```
*/
export class ServiceRegistry {
private services: Map<string, ServiceProvider> = new Map();
/**
* 서비스 팩토리 등록
* @param factory 서비스 인스턴스를 생성하는 팩토리 함수
*/
register(factory: ServiceFactory): void {
const service = factory();
const { id } = service.metadata;
if (this.services.has(id)) {
throw new Error(`서비스 '${id}'가 이미 등록되어 있습니다.`);
}
this.services.set(id, service);
}
/**
* 여러 서비스 팩토리를 한 번에 등록
* @param factories 서비스 팩토리 함수 배열
*/
registerAll(factories: ServiceFactory[]): void {
for (const factory of factories) {
this.register(factory);
}
}
/**
* 모든 서비스 초기화
*/
async initializeAll(): Promise<void> {
const initPromises = Array.from(this.services.values())
.filter((service) => service.initialize)
.map((service) => service.initialize!());
await Promise.all(initPromises);
}
/**
* 모든 서비스 정리
*/
async cleanupAll(): Promise<void> {
const cleanupPromises = Array.from(this.services.values())
.filter((service) => service.cleanup)
.map((service) => service.cleanup!());
await Promise.all(cleanupPromises);
}
/**
* 모든 도구를 MCP 서버에 등록
* @param server MCP 서버 인스턴스
*/
applyToServer(server: McpServer): void {
for (const service of this.services.values()) {
const tools = service.getTools();
for (const tool of tools) {
this.registerTool(server, tool);
}
}
}
/**
* 단일 도구를 MCP 서버에 등록
*/
private registerTool(server: McpServer, tool: ToolRegistration): void {
const metadata = {
...tool.metadata,
outputSchema: createToolOutputSchema(tool.name, tool.metadata.outputSchema),
};
server.registerTool(tool.name, metadata as never, async (args) => {
const started = Date.now();
let result: Awaited<ReturnType<ToolRegistration['handler']>>;
try {
result = await tool.handler(args);
} catch (error) {
diagnosticEvent({ stage: 'tool', operation: tool.name, outcome: 'error', durationMs: Date.now() - started });
const message = error instanceof ServiceError
? JSON.stringify({
error: { code: error.code, message: error.message },
diagnostics: toServiceErrorDiagnostics(error, tool.name.replace(/^[^_]+_/, '')),
})
: getErrorMessage(error);
return {
isError: true,
content: [{ type: 'text' as const, text: message }],
};
}
diagnosticEvent({ stage: 'tool', operation: tool.name, outcome: result.isError ? 'error' : 'ok', durationMs: Date.now() - started });
const content = result.content.map((item) => ({
type: item.type as 'text',
text: item.text,
}));
if (result.isError) {
return {
isError: true,
content,
};
}
return {
content,
structuredContent: buildStructuredContent(result),
};
});
}
/**
* 등록된 서비스 정보 목록 반환
* API 응답용으로 사용됩니다.
*/
getServicesInfo(): ServiceInfo[] {
return Array.from(this.services.values()).map((service) => ({
id: service.metadata.id,
name: service.metadata.name,
version: service.metadata.version,
description: service.metadata.description,
tools: service.getTools().map((tool) => tool.name),
}));
}
/**
* 등록된 모든 도구 이름 반환
*/
getAllToolNames(): string[] {
const toolNames: string[] = [];
for (const service of this.services.values()) {
toolNames.push(...service.getTools().map((tool) => tool.name));
}
return toolNames;
}
/**
* 서비스 개수 반환
*/
get size(): number {
return this.services.size;
}
/**
* 특정 서비스 조회
*/
getService(id: string): ServiceProvider | undefined {
return this.services.get(id);
}
}