korean-law-mcp 4.4.3 → 4.4.4

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.
package/README.md CHANGED
@@ -22,6 +22,12 @@
22
22
 
23
23
  ---
24
24
 
25
+ ## v4.4.1–4.4.3 — 안정성 패치
26
+
27
+ - **v4.4.3**: `zod`를 `^4`로 고정 — 신규 설치가 zod 3.x를 해석해 `listTools` 첫 호출에서 `z.toJSONSchema is not a function`으로 크래시하던 문제 해결
28
+ - **v4.4.2**: `get_annexes` 행정규칙 별표/서식 조회 복구 — 응답 키 `admrulbyl` 우선 파싱 + "...시행세칙" 자동 판별 + 동일 bylSeq 별표/서식 충돌 분리 (#50/#49/#51)
29
+ - **v4.4.1**: 광고 스키마 `required` 버그 수정 — `.default()` 필드(`legal_research.task`·`search_law.display`)가 필수 입력으로 노출되던 문제(`io:"input"` 명시) + `legal_analysis` 비용 옵션 패스스루 + 비호환 scenario 경고 노트
30
+
25
31
  ## v4.4.0 — 노출 도구 통폐합 19개 → 9개 (컨텍스트 52% 감축)
26
32
 
27
33
  MCP 클라이언트가 매 세션 읽는 도구 목록(ListTools)을 ~15.1KB → ~7.2KB로 줄였습니다.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Streamable HTTP 서버 - 리모트 배포용 (MCP 2025-03-26 스펙 준수)
3
+ */
4
+ import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
+ export declare function startSSEServer(server: Server, port: number): Promise<void>;
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Streamable HTTP 서버 - 리모트 배포용 (MCP 2025-03-26 스펙 준수)
3
+ */
4
+ import express from "express";
5
+ import { randomUUID } from "node:crypto";
6
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
7
+ import { InMemoryEventStore } from "@modelcontextprotocol/sdk/examples/shared/inMemoryEventStore.js";
8
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
9
+ import { sessionStore, setSessionApiKey, deleteSession } from "../lib/session-state.js";
10
+ import { VERSION } from "../version.js";
11
+ export async function startSSEServer(server, port) {
12
+ const app = express();
13
+ const transports = {};
14
+ // JSON 파싱 미들웨어 (크기 제한 명시)
15
+ app.use(express.json({ limit: "100kb" }));
16
+ // 유휴 세션 정리 (30분)
17
+ const SESSION_IDLE_TIMEOUT = 30 * 60 * 1000;
18
+ const MAX_SESSIONS = 100;
19
+ setInterval(() => {
20
+ const now = Date.now();
21
+ for (const sid of Object.keys(transports)) {
22
+ const session = transports[sid];
23
+ if (session.lastAccess && now - session.lastAccess > SESSION_IDLE_TIMEOUT) {
24
+ try {
25
+ session.transport.close();
26
+ }
27
+ catch { /* ignore */ }
28
+ delete transports[sid];
29
+ deleteSession(sid);
30
+ }
31
+ }
32
+ }, 5 * 60 * 1000).unref();
33
+ // CORS 및 보안 헤더 설정
34
+ const corsOrigin = process.env.CORS_ORIGIN || "*";
35
+ app.use((req, res, next) => {
36
+ res.header("Access-Control-Allow-Origin", corsOrigin);
37
+ res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD");
38
+ res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, Mcp-Protocol-Version, mcp-protocol-version, Mcp-Session-Id, mcp-session-id, Last-Event-ID, last-event-id, Traceparent, Tracestate");
39
+ res.header("Access-Control-Expose-Headers", "Mcp-Session-Id, Content-Type, Mcp-Protocol-Version, Traceparent, Tracestate");
40
+ res.header("Access-Control-Max-Age", "86400");
41
+ // Security headers (http-server.ts와 동일)
42
+ res.header("X-Content-Type-Options", "nosniff");
43
+ res.header("X-Frame-Options", "DENY");
44
+ res.header("Referrer-Policy", "strict-origin-when-cross-origin");
45
+ res.header("Mcp-Protocol-Version", "2025-03-26");
46
+ if (req.method === "OPTIONS") {
47
+ return res.sendStatus(200);
48
+ }
49
+ next();
50
+ });
51
+ // 헬스체크 엔드포인트
52
+ app.get("/", (req, res) => {
53
+ res.json({
54
+ name: "Korean Law MCP Server",
55
+ version: VERSION,
56
+ status: "running",
57
+ protocol: "streamable-http",
58
+ endpoints: {
59
+ mcp: "/mcp",
60
+ health: "/health"
61
+ }
62
+ });
63
+ });
64
+ app.get("/health", (req, res) => {
65
+ res.json({ status: "ok", timestamp: new Date().toISOString() });
66
+ });
67
+ // MCP POST 엔드포인트 (초기화 및 요청 처리)
68
+ app.post("/mcp", async (req, res) => {
69
+ const sessionId = req.headers["mcp-session-id"];
70
+ // API 키 추출 (http-server.ts와 동일 패턴)
71
+ const apiKeyFromHeader = req.headers["apikey"] ||
72
+ req.headers["law_oc"] ||
73
+ req.headers["law-oc"] ||
74
+ req.headers["LAW_OC"] ||
75
+ req.headers["x-api-key"] ||
76
+ req.headers["authorization"]?.replace(/^Bearer\s+/i, "") ||
77
+ req.headers["x-law-oc"];
78
+ if (sessionId) {
79
+ console.error(`Received MCP request for session: ${sessionId.slice(0, 8)}...`);
80
+ }
81
+ else {
82
+ console.error("New MCP request (no session ID)");
83
+ }
84
+ try {
85
+ let transport;
86
+ if (sessionId && transports[sessionId]) {
87
+ // 기존 세션 재사용 + 접근 시각 갱신
88
+ ;
89
+ transports[sessionId].lastAccess = Date.now();
90
+ transport = transports[sessionId].transport;
91
+ // API 키 업데이트 (헤더에서 제공된 경우)
92
+ if (apiKeyFromHeader) {
93
+ setSessionApiKey(sessionId, apiKeyFromHeader);
94
+ }
95
+ // AsyncLocalStorage로 세션 ID 격리 (동시 요청 안전)
96
+ await sessionStore.run(sessionId, async () => {
97
+ await transport.handleRequest(req, res, req.body);
98
+ });
99
+ return;
100
+ }
101
+ else if (!sessionId && isInitializeRequest(req.body)) {
102
+ // 새 세션 초기화
103
+ // 세션 수 제한 — transport 생성 전에 체크하여 리소스 누수 방지
104
+ if (Object.keys(transports).length >= MAX_SESSIONS) {
105
+ res.status(503).json({
106
+ jsonrpc: "2.0",
107
+ error: { code: -32000, message: `Max sessions (${MAX_SESSIONS}) reached. Try again later.` },
108
+ id: null,
109
+ });
110
+ return;
111
+ }
112
+ const eventStore = new InMemoryEventStore();
113
+ transport = new StreamableHTTPServerTransport({
114
+ sessionIdGenerator: () => randomUUID(),
115
+ eventStore,
116
+ onsessioninitialized: (newSessionId) => {
117
+ transports[newSessionId] = { transport, lastAccess: Date.now() };
118
+ if (apiKeyFromHeader) {
119
+ setSessionApiKey(newSessionId, apiKeyFromHeader);
120
+ }
121
+ }
122
+ });
123
+ // 세션 종료 시 정리
124
+ transport.onclose = () => {
125
+ const sid = transport.sessionId;
126
+ if (sid && transports[sid]) {
127
+ console.error(`Transport closed for session ${sid.slice(0, 8)}...`);
128
+ delete transports[sid];
129
+ deleteSession(sid);
130
+ }
131
+ };
132
+ // 서버 연결
133
+ await server.connect(transport);
134
+ await transport.handleRequest(req, res, req.body);
135
+ return;
136
+ }
137
+ else {
138
+ // 잘못된 요청
139
+ res.status(400).json({
140
+ jsonrpc: "2.0",
141
+ error: {
142
+ code: -32000,
143
+ message: "Invalid request: missing session ID or not an initialization request"
144
+ },
145
+ id: null
146
+ });
147
+ return;
148
+ }
149
+ }
150
+ catch (error) {
151
+ console.error("Error handling MCP POST request:", error);
152
+ if (!res.headersSent) {
153
+ res.status(500).json({
154
+ jsonrpc: "2.0",
155
+ error: {
156
+ code: -32603,
157
+ message: "Internal server error"
158
+ },
159
+ id: null
160
+ });
161
+ }
162
+ }
163
+ });
164
+ // MCP GET 엔드포인트 (SSE 스트림)
165
+ app.get("/mcp", async (req, res) => {
166
+ const sessionId = req.headers["mcp-session-id"];
167
+ if (!sessionId || !transports[sessionId]) {
168
+ res.status(400).send("Invalid or missing session ID");
169
+ return;
170
+ }
171
+ const lastEventId = req.headers["last-event-id"];
172
+ if (lastEventId) {
173
+ console.error(`Client reconnecting with Last-Event-ID: ${lastEventId}`);
174
+ }
175
+ else {
176
+ console.error(`Establishing SSE stream for session ${sessionId.slice(0, 8)}...`);
177
+ }
178
+ try {
179
+ const transport = transports[sessionId].transport;
180
+ await transport.handleRequest(req, res);
181
+ }
182
+ catch (error) {
183
+ console.error("[GET /mcp] Error:", error);
184
+ if (!res.headersSent) {
185
+ res.status(500).send("Internal server error");
186
+ }
187
+ }
188
+ });
189
+ // MCP DELETE 엔드포인트 (세션 종료)
190
+ app.delete("/mcp", async (req, res) => {
191
+ const sessionId = req.headers["mcp-session-id"];
192
+ if (!sessionId || !transports[sessionId]) {
193
+ res.status(400).send("Invalid or missing session ID");
194
+ return;
195
+ }
196
+ console.error(`Session termination request for ${sessionId.slice(0, 8)}...`);
197
+ try {
198
+ const transport = transports[sessionId].transport;
199
+ await transport.handleRequest(req, res);
200
+ delete transports[sessionId];
201
+ deleteSession(sessionId);
202
+ console.error(`Session removed: ${sessionId.slice(0, 8)}...`);
203
+ }
204
+ catch (error) {
205
+ console.error("Error handling session termination:", error);
206
+ if (!res.headersSent) {
207
+ res.status(500).send("Error processing session termination");
208
+ }
209
+ }
210
+ });
211
+ // 서버 시작
212
+ app.listen(port, "0.0.0.0", () => {
213
+ console.error(`✓ Korean Law MCP server (Streamable HTTP) listening on port ${port}`);
214
+ console.error(`✓ MCP endpoint: http://0.0.0.0:${port}/mcp`);
215
+ console.error(`✓ Health check: http://0.0.0.0:${port}/health`);
216
+ });
217
+ // 종료 처리
218
+ process.on("SIGINT", async () => {
219
+ console.error("Shutting down server...");
220
+ for (const sessionId in transports) {
221
+ try {
222
+ await transports[sessionId].transport.close();
223
+ delete transports[sessionId];
224
+ deleteSession(sessionId);
225
+ }
226
+ catch (error) {
227
+ console.error(`Error closing transport ${sessionId}:`, error);
228
+ }
229
+ }
230
+ process.exit(0);
231
+ });
232
+ }
@@ -293,8 +293,14 @@ function findMatchingAnnex(annexList, annexSelector, knd) {
293
293
  }
294
294
  return selectorNumbers.some((num) => titleMatchesAnnexNumber(annexTitle, num));
295
295
  });
296
- if (matches.length === 0)
296
+ if (matches.length === 0) {
297
+ // 번호가 안 맞아도 별표가 유일 1건이면 그 별표를 정답으로 폴백.
298
+ // 여권법 시행령 '수수료 및 사무의 대행에 드는 비용(제39조 관련)'처럼 번호 없는 단일 별표는
299
+ // 모델이 "별표1" 등 임의 번호로 불러도 매칭 0건 → NOT_FOUND로 새는 대신 유일 별표를 반환.
300
+ if (annexList.length === 1)
301
+ return annexList[0];
297
302
  return undefined;
303
+ }
298
304
  if (matches.length === 1)
299
305
  return matches[0];
300
306
  // 별표번호 충돌 → 별표종류("별표"/"서식")로 구분
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "korean-law-mcp",
3
- "version": "4.4.3",
3
+ "version": "4.4.4",
4
4
  "description": "법제처 42개 API → 9개 MCP 도구. 법령·판례·조례·조약 + 다단계 리서치(legal_research, 8 task) + 정밀분석(legal_analysis: 인용검증·판례생사·행위시법·영향그래프) + 시점 비교(time_travel) + 상황별 5단계 안내(action_plan) + 국세청 해석례(nts)",
5
5
  "type": "module",
6
6
  "main": "build/index.js",