@channel.io/be-user-chat-mcp
Version:
Backend UserChat Model Context Protocol server for Channel.io
60 lines • 2.88 kB
JavaScript
// Helper to format settled promise results
// This could be moved to a shared utility if used in multiple places
export const formatResult = (result, notFoundMsg, errorMsg) => {
if (result.status === "fulfilled") {
return result.value ?? notFoundMsg; // Handle null/undefined from domain functions
}
else {
console.error(`${errorMsg}:`, result.reason); // Log the actual error
return {
error: true,
message: `${errorMsg}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,
};
}
};
/**
* MCP 툴을 등록하는 범용 헬퍼 함수입니다.
* 입력 스키마 유효성 검사, 데이터 페칭, 결과 포맷팅, 에러 처리 등
* 공통 로직을 내부적으로 처리합니다.
*/
export function registerMcpTool(server, toolName, inputSchema, fetchDataFn, getContext) {
server.tool(toolName,
// inputSchema가 항상 z.object() 형태라고 가정합니다.
// 만약 다른 타입의 스키마(예: z.string())가 직접 사용될 경우, 이 부분은 조정이 필요할 수 있습니다.
// 현재 제공된 코드는 ZodObject의 shape를 사용하므로 그대로 유지합니다.
inputSchema.shape, async (args) => {
const parseResult = inputSchema.safeParse(args);
if (!parseResult.success) {
const errorMessage = `Invalid input for ${toolName}: ${JSON.stringify(parseResult.error.format())}`;
console.error(errorMessage);
// MCP 명세에 따라 적절한 에러 응답을 반환하거나, 에러를 throw 할 수 있습니다.
// 현재 코드는 Error를 throw하므로 해당 방식을 따릅니다.
throw new Error(errorMessage);
}
const typedInput = parseResult.data;
try {
// RequestContext를 가져와서 fetchDataFn에 전달
const context = getContext();
const data = await fetchDataFn(typedInput, context);
return {
content: [
{
type: "text",
text: JSON.stringify(data, null, 2),
},
],
};
}
catch (error) {
const message = error instanceof Error
? error.message
: "An unknown error occurred during tool execution";
console.error(`[Tool Error - ${toolName}] Failed to execute: ${message}`, error);
// 클라이언트에게 전달될 에러 메시지
throw new Error(`Failed to execute ${toolName}: ${message}`);
}
});
// 기존 코드의 console.error 대신 console.log 또는 다른 로깅 레벨 사용을 고려할 수 있습니다.
console.log(`Registered tool: ${toolName}`);
}
//# sourceMappingURL=helper.util.js.map