@mandujs/mcp 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,174 @@
1
+ /**
2
+ * MCP Config Watcher
3
+ *
4
+ * DNA-006 설정 핫 리로드와 MCP 서버 통합
5
+ */
6
+
7
+ import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
8
+ import { watchConfig, hasConfigChanged, type ManduConfig } from "@mandujs/core";
9
+ import { mcpToolRegistry } from "../registry/mcp-tool-registry.js";
10
+
11
+ /**
12
+ * MCP Config Watcher 옵션
13
+ */
14
+ export interface McpConfigWatcherOptions {
15
+ /** MCP Server 인스턴스 */
16
+ server?: Server;
17
+ /** 설정 변경 콜백 */
18
+ onReload?: (config: ManduConfig) => void | Promise<void>;
19
+ /** MCP 설정 변경 시 콜백 */
20
+ onMcpConfigChange?: (config: ManduConfig) => void | Promise<void>;
21
+ /** 에러 콜백 */
22
+ onError?: (error: unknown) => void;
23
+ /** 디바운스 딜레이 (ms) */
24
+ debounceMs?: number;
25
+ }
26
+
27
+ /**
28
+ * Config Watcher 결과
29
+ */
30
+ export interface McpConfigWatcher {
31
+ /** 감시 중지 */
32
+ stop: () => void;
33
+ /** 수동 리로드 */
34
+ reload: () => Promise<ManduConfig | undefined>;
35
+ /** 현재 설정 */
36
+ getConfig: () => ManduConfig | undefined;
37
+ }
38
+
39
+ /**
40
+ * MCP 서버 설정 감시 시작
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const watcher = await startMcpConfigWatcher(projectRoot, {
45
+ * server,
46
+ * onReload: (config) => {
47
+ * console.log("Config reloaded:", config);
48
+ * },
49
+ * });
50
+ *
51
+ * // 나중에 중지
52
+ * watcher.stop();
53
+ * ```
54
+ */
55
+ export async function startMcpConfigWatcher(
56
+ projectRoot: string,
57
+ options: McpConfigWatcherOptions = {}
58
+ ): Promise<McpConfigWatcher> {
59
+ const {
60
+ server,
61
+ onReload,
62
+ onMcpConfigChange,
63
+ onError,
64
+ debounceMs = 200,
65
+ } = options;
66
+
67
+ const watcher = await watchConfig(
68
+ projectRoot,
69
+ async (newConfig, event) => {
70
+ // MCP 서버에 알림
71
+ if (server) {
72
+ try {
73
+ await server.sendLoggingMessage({
74
+ level: "info",
75
+ logger: "mandu-config",
76
+ data: {
77
+ type: "config_reload",
78
+ changedSections: event.changedSections,
79
+ path: event.path,
80
+ },
81
+ });
82
+ } catch {
83
+ // 알림 실패 무시
84
+ }
85
+ }
86
+
87
+ // MCP 관련 설정 변경 확인
88
+ if (event.previous && event.current) {
89
+ if (hasConfigChanged(event.previous, event.current, "mcp")) {
90
+ // MCP 설정 변경 시 도구 재초기화 등 필요한 작업
91
+ if (server) {
92
+ try {
93
+ await server.sendLoggingMessage({
94
+ level: "warning",
95
+ logger: "mandu-config",
96
+ data: {
97
+ type: "mcp_config_changed",
98
+ message: "MCP configuration changed. Some tools may need reinitialization.",
99
+ },
100
+ });
101
+ } catch {
102
+ // 알림 실패 무시
103
+ }
104
+ }
105
+
106
+ await onMcpConfigChange?.(newConfig);
107
+ }
108
+
109
+ // Guard 설정 변경 확인
110
+ if (hasConfigChanged(event.previous, event.current, "guard")) {
111
+ if (server) {
112
+ try {
113
+ await server.sendLoggingMessage({
114
+ level: "info",
115
+ logger: "mandu-config",
116
+ data: {
117
+ type: "guard_config_changed",
118
+ message: "Guard configuration changed. Architecture rules updated.",
119
+ },
120
+ });
121
+ } catch {
122
+ // 알림 실패 무시
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ // 일반 콜백
129
+ await onReload?.(newConfig);
130
+ },
131
+ {
132
+ debounceMs,
133
+ immediate: false,
134
+ onError: (err) => {
135
+ console.error("[MCP:ConfigWatcher] Error:", err);
136
+
137
+ if (server) {
138
+ server.sendLoggingMessage({
139
+ level: "error",
140
+ logger: "mandu-config",
141
+ data: {
142
+ type: "config_error",
143
+ error: err instanceof Error ? err.message : String(err),
144
+ },
145
+ }).catch(() => {});
146
+ }
147
+
148
+ onError?.(err);
149
+ },
150
+ }
151
+ );
152
+
153
+ return watcher;
154
+ }
155
+
156
+ /**
157
+ * 설정 변경 시 도구 재등록이 필요한지 확인
158
+ */
159
+ export function needsToolReregistration(
160
+ previous: ManduConfig | undefined,
161
+ current: ManduConfig | undefined
162
+ ): boolean {
163
+ if (!previous || !current) return false;
164
+
165
+ // MCP 플러그인 설정 변경
166
+ const prevPlugins = (previous as Record<string, unknown>).mcpPlugins;
167
+ const currPlugins = (current as Record<string, unknown>).mcpPlugins;
168
+
169
+ if (JSON.stringify(prevPlugins) !== JSON.stringify(currPlugins)) {
170
+ return true;
171
+ }
172
+
173
+ return false;
174
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * MCP Hooks
3
+ *
4
+ * DNA-016 기반 도구 실행 훅
5
+ */
6
+
7
+ export {
8
+ mcpHookRegistry,
9
+ registerDefaultMcpHooks,
10
+ slowToolLoggingHook,
11
+ statsCollectorHook,
12
+ getToolStats,
13
+ resetToolStats,
14
+ createArgValidationHook,
15
+ type McpToolContext,
16
+ type McpPreToolHook,
17
+ type McpPostToolHook,
18
+ } from "./mcp-hooks.js";
19
+
20
+ export {
21
+ startMcpConfigWatcher,
22
+ type McpConfigWatcherOptions,
23
+ } from "./config-watcher.js";
@@ -0,0 +1,227 @@
1
+ /**
2
+ * MCP Pre/Post Tool Hooks
3
+ *
4
+ * DNA-016 Pre-Action 훅 시스템 기반 MCP 도구 훅
5
+ */
6
+
7
+ import type { ManduConfig } from "@mandujs/core";
8
+
9
+ /**
10
+ * MCP 도구 실행 컨텍스트
11
+ */
12
+ export interface McpToolContext {
13
+ /** 도구 이름 */
14
+ toolName: string;
15
+ /** 도구 인자 */
16
+ args: Record<string, unknown>;
17
+ /** 프로젝트 루트 */
18
+ projectRoot: string;
19
+ /** Mandu 설정 */
20
+ config?: ManduConfig;
21
+ /** 실행 시작 시간 */
22
+ startTime: number;
23
+ /** 커스텀 데이터 (훅 간 공유용) */
24
+ custom?: Record<string, unknown>;
25
+ }
26
+
27
+ /**
28
+ * Pre-Tool 훅 타입
29
+ *
30
+ * 도구 실행 전에 호출됨
31
+ * - 권한 검사
32
+ * - 인자 검증
33
+ * - 로깅
34
+ */
35
+ export type McpPreToolHook = (ctx: McpToolContext) => void | Promise<void>;
36
+
37
+ /**
38
+ * Post-Tool 훅 타입
39
+ *
40
+ * 도구 실행 후에 호출됨
41
+ * - 결과 로깅
42
+ * - 통계 수집
43
+ * - 정리 작업
44
+ */
45
+ export type McpPostToolHook = (
46
+ ctx: McpToolContext,
47
+ result: unknown,
48
+ error?: unknown
49
+ ) => void | Promise<void>;
50
+
51
+ /**
52
+ * MCP 훅 레지스트리
53
+ */
54
+ class McpHookRegistry {
55
+ private preHooks: Array<{ hook: McpPreToolHook; priority: number }> = [];
56
+ private postHooks: Array<{ hook: McpPostToolHook; priority: number }> = [];
57
+
58
+ /**
59
+ * Pre-Tool 훅 등록
60
+ *
61
+ * @param hook - 훅 함수
62
+ * @param priority - 우선순위 (낮을수록 먼저 실행, 기본값 100)
63
+ * @returns 등록 해제 함수
64
+ */
65
+ registerPreHook(hook: McpPreToolHook, priority = 100): () => void {
66
+ const entry = { hook, priority };
67
+ this.preHooks.push(entry);
68
+ this.preHooks.sort((a, b) => a.priority - b.priority);
69
+
70
+ return () => {
71
+ const idx = this.preHooks.indexOf(entry);
72
+ if (idx >= 0) this.preHooks.splice(idx, 1);
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Post-Tool 훅 등록
78
+ *
79
+ * @param hook - 훅 함수
80
+ * @param priority - 우선순위 (낮을수록 먼저 실행, 기본값 100)
81
+ * @returns 등록 해제 함수
82
+ */
83
+ registerPostHook(hook: McpPostToolHook, priority = 100): () => void {
84
+ const entry = { hook, priority };
85
+ this.postHooks.push(entry);
86
+ this.postHooks.sort((a, b) => a.priority - b.priority);
87
+
88
+ return () => {
89
+ const idx = this.postHooks.indexOf(entry);
90
+ if (idx >= 0) this.postHooks.splice(idx, 1);
91
+ };
92
+ }
93
+
94
+ /**
95
+ * 모든 Pre-Tool 훅 실행
96
+ */
97
+ async runPreHooks(ctx: McpToolContext): Promise<void> {
98
+ for (const { hook } of this.preHooks) {
99
+ try {
100
+ await hook(ctx);
101
+ } catch (err) {
102
+ console.error(`[MCP:PreHook] Error in hook for ${ctx.toolName}:`, err);
103
+ throw err; // Pre 훅 에러는 도구 실행을 중단
104
+ }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 모든 Post-Tool 훅 실행
110
+ */
111
+ async runPostHooks(ctx: McpToolContext, result: unknown, error?: unknown): Promise<void> {
112
+ for (const { hook } of this.postHooks) {
113
+ try {
114
+ await hook(ctx, result, error);
115
+ } catch (err) {
116
+ // Post 훅 에러는 로깅만 하고 계속 진행
117
+ console.error(`[MCP:PostHook] Error in hook for ${ctx.toolName}:`, err);
118
+ }
119
+ }
120
+ }
121
+
122
+ /**
123
+ * 모든 훅 제거
124
+ */
125
+ clear(): void {
126
+ this.preHooks = [];
127
+ this.postHooks = [];
128
+ }
129
+
130
+ /**
131
+ * 등록된 훅 수
132
+ */
133
+ get counts(): { pre: number; post: number } {
134
+ return {
135
+ pre: this.preHooks.length,
136
+ post: this.postHooks.length,
137
+ };
138
+ }
139
+ }
140
+
141
+ /**
142
+ * 전역 MCP 훅 레지스트리
143
+ */
144
+ export const mcpHookRegistry = new McpHookRegistry();
145
+
146
+ // ============================================
147
+ // 기본 훅 구현
148
+ // ============================================
149
+
150
+ /**
151
+ * 실행 시간 로깅 훅
152
+ */
153
+ export const slowToolLoggingHook: McpPostToolHook = (ctx, _result, _error) => {
154
+ const duration = Date.now() - ctx.startTime;
155
+ if (duration > 5000) {
156
+ console.warn(`[MCP] Slow tool execution: ${ctx.toolName} (${duration}ms)`);
157
+ }
158
+ };
159
+
160
+ /**
161
+ * 도구별 통계 수집 훅
162
+ */
163
+ const toolStats = new Map<string, { calls: number; errors: number; totalDuration: number }>();
164
+
165
+ export const statsCollectorHook: McpPostToolHook = (ctx, _result, error) => {
166
+ const duration = Date.now() - ctx.startTime;
167
+ const stats = toolStats.get(ctx.toolName) ?? { calls: 0, errors: 0, totalDuration: 0 };
168
+
169
+ stats.calls += 1;
170
+ stats.totalDuration += duration;
171
+ if (error) stats.errors += 1;
172
+
173
+ toolStats.set(ctx.toolName, stats);
174
+ };
175
+
176
+ /**
177
+ * 도구 통계 조회
178
+ */
179
+ export function getToolStats(): Record<string, { calls: number; errors: number; avgDuration: number }> {
180
+ const result: Record<string, { calls: number; errors: number; avgDuration: number }> = {};
181
+
182
+ for (const [name, stats] of toolStats) {
183
+ result[name] = {
184
+ calls: stats.calls,
185
+ errors: stats.errors,
186
+ avgDuration: stats.calls > 0 ? Math.round(stats.totalDuration / stats.calls) : 0,
187
+ };
188
+ }
189
+
190
+ return result;
191
+ }
192
+
193
+ /**
194
+ * 도구 통계 초기화
195
+ */
196
+ export function resetToolStats(): void {
197
+ toolStats.clear();
198
+ }
199
+
200
+ /**
201
+ * 인자 검증 훅 생성기
202
+ */
203
+ export function createArgValidationHook(
204
+ validations: Record<string, (args: Record<string, unknown>) => boolean | string>
205
+ ): McpPreToolHook {
206
+ return (ctx) => {
207
+ const validator = validations[ctx.toolName];
208
+ if (!validator) return;
209
+
210
+ const result = validator(ctx.args);
211
+ if (result === true) return;
212
+
213
+ const message = typeof result === "string" ? result : `Invalid arguments for ${ctx.toolName}`;
214
+ throw new Error(message);
215
+ };
216
+ }
217
+
218
+ /**
219
+ * 기본 훅 등록
220
+ */
221
+ export function registerDefaultMcpHooks(): void {
222
+ // 느린 도구 경고 (우선순위 낮음 - 마지막에 실행)
223
+ mcpHookRegistry.registerPostHook(slowToolLoggingHook, 900);
224
+
225
+ // 통계 수집 (우선순위 높음 - 먼저 실행)
226
+ mcpHookRegistry.registerPostHook(statsCollectorHook, 10);
227
+ }
package/src/index.ts CHANGED
@@ -1,20 +1,106 @@
1
- #!/usr/bin/env bun
2
-
1
+ #!/usr/bin/env bun
2
+
3
+ /**
4
+ * @mandujs/mcp - MCP Server for Mandu Framework
5
+ *
6
+ * DNA 기능 통합:
7
+ * - DNA-001: 플러그인 기반 도구 등록
8
+ * - DNA-006: 설정 핫 리로드
9
+ * - DNA-007: 에러 추출 및 분류
10
+ * - DNA-008: 구조화된 로깅
11
+ * - DNA-016: Pre/Post 도구 훅
12
+ */
13
+
14
+ // Main exports
15
+ export { ManduMcpServer, startServer } from "./server.js";
16
+
17
+ // Registry exports (DNA-001)
18
+ export {
19
+ McpToolRegistry,
20
+ mcpToolRegistry,
21
+ type ToolRegistration,
22
+ type RegistryEvent,
23
+ type RegistryDump,
24
+ } from "./registry/index.js";
25
+
26
+ // Adapter exports
27
+ export {
28
+ toolToPlugin,
29
+ pluginToTool,
30
+ moduleToPlugins,
31
+ pluginsToTools,
32
+ pluginsToHandlers,
33
+ monitorEventToRecord,
34
+ recordToMonitorEvent,
35
+ } from "./adapters/index.js";
36
+
37
+ // Executor exports (DNA-007)
38
+ export {
39
+ formatMcpError,
40
+ createToolResponse,
41
+ isErrorResponse,
42
+ extractErrorFromResponse,
43
+ logToolError,
44
+ ToolExecutor,
45
+ createToolExecutor,
46
+ type McpErrorResponse,
47
+ type McpToolResponse,
48
+ type ToolExecutorOptions,
49
+ type ExecutionResult,
50
+ } from "./executor/index.js";
51
+
52
+ // Hook exports (DNA-016)
53
+ export {
54
+ mcpHookRegistry,
55
+ registerDefaultMcpHooks,
56
+ slowToolLoggingHook,
57
+ statsCollectorHook,
58
+ getToolStats,
59
+ resetToolStats,
60
+ createArgValidationHook,
61
+ startMcpConfigWatcher,
62
+ type McpToolContext,
63
+ type McpPreToolHook,
64
+ type McpPostToolHook,
65
+ type McpConfigWatcherOptions,
66
+ } from "./hooks/index.js";
67
+
68
+ // Logging exports (DNA-008)
69
+ export {
70
+ createMcpActivityTransport,
71
+ setupMcpLogging,
72
+ teardownMcpLogging,
73
+ dispatchMonitorEvent,
74
+ createMcpLogRecord,
75
+ MCP_TRANSPORT_ID,
76
+ type McpTransportOptions,
77
+ } from "./logging/index.js";
78
+
79
+ // Tools exports
80
+ export {
81
+ registerBuiltinTools,
82
+ getToolCounts,
83
+ getToolsSummary,
84
+ } from "./tools/index.js";
85
+
86
+ // CLI entry point
3
87
  import { startServer } from "./server.js";
4
88
  import path from "path";
5
89
 
6
- // Start the MCP server
7
- const args = process.argv.slice(2);
8
- const globalMode = args.includes("--global");
9
- const rootIndex = args.indexOf("--root");
10
- const rootArg = rootIndex >= 0 ? args[rootIndex + 1] : undefined;
11
- const projectRoot = rootArg
12
- ? path.resolve(rootArg)
13
- : globalMode
14
- ? process.cwd()
15
- : undefined;
16
-
17
- startServer(projectRoot).catch((error) => {
18
- console.error("Failed to start Mandu MCP server:", error);
19
- process.exit(1);
20
- });
90
+ // Start server if run directly
91
+ if (import.meta.main) {
92
+ const args = process.argv.slice(2);
93
+ const globalMode = args.includes("--global");
94
+ const rootIndex = args.indexOf("--root");
95
+ const rootArg = rootIndex >= 0 ? args[rootIndex + 1] : undefined;
96
+ const projectRoot = rootArg
97
+ ? path.resolve(rootArg)
98
+ : globalMode
99
+ ? process.cwd()
100
+ : undefined;
101
+
102
+ startServer(projectRoot).catch((error) => {
103
+ console.error("Failed to start Mandu MCP server:", error);
104
+ process.exit(1);
105
+ });
106
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * MCP Logging
3
+ *
4
+ * DNA-008 로깅 통합
5
+ */
6
+
7
+ export {
8
+ createMcpActivityTransport,
9
+ setupMcpLogging,
10
+ teardownMcpLogging,
11
+ dispatchMonitorEvent,
12
+ createMcpLogRecord,
13
+ MCP_TRANSPORT_ID,
14
+ type McpTransportOptions,
15
+ } from "./mcp-transport.js";
@@ -0,0 +1,134 @@
1
+ /**
2
+ * MCP LogTransport Integration
3
+ *
4
+ * DNA-008 로깅 시스템과 MCP ActivityMonitor 통합
5
+ */
6
+
7
+ import {
8
+ attachLogTransport,
9
+ detachLogTransport,
10
+ type LogTransport,
11
+ type LogTransportRecord,
12
+ } from "@mandujs/core";
13
+ import { monitorEventToRecord, type MonitorEvent } from "../adapters/monitor-adapter.js";
14
+
15
+ /**
16
+ * MCP 로깅 Transport ID
17
+ */
18
+ export const MCP_TRANSPORT_ID = "mcp-activity";
19
+
20
+ /**
21
+ * MCP Activity Transport 옵션
22
+ */
23
+ export interface McpTransportOptions {
24
+ /** 로그 파일 경로 (선택) */
25
+ logFile?: string;
26
+ /** 콘솔 출력 여부 */
27
+ consoleOutput?: boolean;
28
+ /** 커스텀 핸들러 */
29
+ onRecord?: (record: LogTransportRecord) => void;
30
+ }
31
+
32
+ /**
33
+ * MCP Activity Transport 생성
34
+ *
35
+ * ActivityMonitor의 이벤트를 DNA-008 TransportRegistry로 전달
36
+ */
37
+ export function createMcpActivityTransport(
38
+ options: McpTransportOptions = {}
39
+ ): LogTransport {
40
+ const { consoleOutput = false, onRecord } = options;
41
+
42
+ return (record: LogTransportRecord) => {
43
+ // MCP 관련 로그만 처리
44
+ const source = record.meta?.source;
45
+ if (source !== "mcp" && source !== "tool" && source !== "watch") {
46
+ return;
47
+ }
48
+
49
+ // 커스텀 핸들러
50
+ if (onRecord) {
51
+ onRecord(record);
52
+ }
53
+
54
+ // 콘솔 출력
55
+ if (consoleOutput) {
56
+ const prefix = `[MCP:${source}]`;
57
+ const msg = record.error?.message || (record.meta?.message as string) || "";
58
+
59
+ switch (record.level) {
60
+ case "error":
61
+ console.error(prefix, msg, record.meta);
62
+ break;
63
+ case "warn":
64
+ console.warn(prefix, msg, record.meta);
65
+ break;
66
+ default:
67
+ console.log(prefix, msg, record.meta);
68
+ }
69
+ }
70
+ };
71
+ }
72
+
73
+ /**
74
+ * MCP 로깅 설정
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * setupMcpLogging({
79
+ * consoleOutput: true,
80
+ * onRecord: (record) => {
81
+ * // 커스텀 처리
82
+ * },
83
+ * });
84
+ * ```
85
+ */
86
+ export function setupMcpLogging(options: McpTransportOptions = {}): void {
87
+ const transport = createMcpActivityTransport(options);
88
+ attachLogTransport(MCP_TRANSPORT_ID, transport, { minLevel: "info" });
89
+ }
90
+
91
+ /**
92
+ * MCP 로깅 해제
93
+ */
94
+ export function teardownMcpLogging(): void {
95
+ detachLogTransport(MCP_TRANSPORT_ID);
96
+ }
97
+
98
+ /**
99
+ * MonitorEvent를 DNA-008 시스템으로 전송
100
+ *
101
+ * ActivityMonitor에서 이 함수를 호출하여 로그 통합
102
+ */
103
+ export function dispatchMonitorEvent(event: MonitorEvent): void {
104
+ const record = monitorEventToRecord(event);
105
+
106
+ // 직접 transport로 전달하지 않고,
107
+ // 다른 transport들도 받을 수 있도록 registry를 통해 dispatch
108
+ // (transportRegistry.dispatch는 core에서 export 필요)
109
+
110
+ // 임시: 콘솔 출력
111
+ if (event.severity === "error") {
112
+ console.error(`[MCP:${event.source}] ${event.message || event.type}`, event.data);
113
+ }
114
+ }
115
+
116
+ /**
117
+ * MCP 로그 레코드 생성 헬퍼
118
+ */
119
+ export function createMcpLogRecord(
120
+ level: "debug" | "info" | "warn" | "error",
121
+ source: "mcp" | "tool" | "watch",
122
+ message: string,
123
+ data?: Record<string, unknown>
124
+ ): LogTransportRecord {
125
+ return {
126
+ timestamp: new Date().toISOString(),
127
+ level,
128
+ meta: {
129
+ source,
130
+ message,
131
+ ...data,
132
+ },
133
+ };
134
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * MCP Registry
3
+ *
4
+ * 도구 레지스트리 및 관련 유틸리티
5
+ */
6
+
7
+ export {
8
+ McpToolRegistry,
9
+ mcpToolRegistry,
10
+ type ToolRegistration,
11
+ type RegistryEvent,
12
+ type RegistryDump,
13
+ } from "./mcp-tool-registry.js";