geo-figure-mcp 0.2.4 → 0.2.6
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 +6 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/src/data.js +33 -4
- package/src/tools.js +107 -23
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.
|
|
1
|
+
# geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.6)
|
|
2
2
|
|
|
3
3
|
만든 사람: 김한솔 (한백고등학교 지리 교사)
|
|
4
4
|
|
|
@@ -74,11 +74,15 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
|
|
|
74
74
|
- 원격 서버를 쓸 때는 `"serverUrl": "https://…/mcp?token=비밀번호"` 한 줄로 등록합니다(`url`·`httpUrl` 이 아님).
|
|
75
75
|
|
|
76
76
|
## 내장 통계와 지도 이름 맞추기
|
|
77
|
+
|
|
78
|
+
- 지도와 그래프에 필요한 항목은 `bundle.items`, 지역은 `bundle.regions`(정확한 `mapName` 또는 통계표 지역명)로 고릅니다. 한 시·도의 지도용 시·군·구를 모두 받으려면 `bundle.within`을 씁니다. 예를 들어 `find_data`에 `{"source":"bundle","bundle":{"key":"daytime-population","period":"2020","items":["주간 인구 지수"],"within":["경기"]}}`를 보내면 경기도 시·군의 해당 지수만 받습니다.
|
|
77
79
|
- 내장 자료의 각 행에는 `mapName`(예: '경기 화성시')이 붙어 있어 지도 기호·단계 구분에 그대로 씁니다.
|
|
78
80
|
- 일반구(수원시 장안구 등)는 지도에서 시로 합쳐 그리므로 `mapName` 이 없고, 시 합계 행을 씁니다.
|
|
79
81
|
- 지도 판은 자료 연도에 맞춥니다. 2026년 7월 이전 자료는 2025년 판(17개 시·도)을 씁니다. 결과의 `mapEdition` 을 지도 `edition` 에 넣으면 됩니다.
|
|
80
82
|
- 단계 구분에 지도에 없는 이름이 섞이면 조용히 빠지지 않고 오류로 알립니다.
|
|
81
83
|
|
|
84
|
+
- 그림 명세는 `guide(topic:"spec", section:"map")`처럼 지도·그래프·지형 중 필요한 부분만 볼 수 있습니다(`map`, `chart`, `terrain`). 기출 기후 지점은 `summary:true`로 이름과 기후 기호만, 기후 통계는 `indicators:["temp"]` 또는 `["precip"]`로 필요한 값만 조회할 수 있습니다. 지도 지역명은 `list_regions`에 `query`와 `edition`을 지정해 확인합니다.
|
|
85
|
+
|
|
82
86
|
## 선생님들은 어떻게 쓰나 — 두 가지 방법
|
|
83
87
|
|
|
84
88
|
| | ① 내 컴퓨터에 설치 (권장) | ② 원격 서버 주소 붙이기 |
|
|
@@ -117,6 +121,7 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
|
|
|
117
121
|
- 단계를 손으로 바꿀 땐 범례 칸을 고르고 서식 복사(붓)로 지역에 칠하면 됩니다.
|
|
118
122
|
- **한글**: 그림 선택 → 마우스 오른쪽 → 개체 풀기 **한 번**. 조각이 제자리에 남습니다.
|
|
119
123
|
- 그림이 쪽에 다 안 들어가면 제목부터 다음 쪽으로 넘어갑니다(겹치지 않음).
|
|
124
|
+
- **범례·기호만 바꾸기**: 로컬에서 `preview_figures`에 `saved: {name, legend, labelStyle}`처럼 파일 이름과 바꿀 내용만 보냅니다. `labels`에는 기호를 바꿀 기존 지도 지역만 적습니다. 그림이나 지도가 여러 개라면 `figure`와 `part`로 대상을 지정할 수 있습니다(1부터). 수정 시안을 확인한 후 `make_figures`에 `previewId`, 새 이름, 출력 형식을 보냅니다. 지도 기호를 바꿨다면 그래프 기호와 정답표를 확인합니다.
|
|
120
125
|
- **크게 바꿀 땐 AI에게 말로**: 설계도를 읽어 그 부분만 바꿔 다시 만듭니다(open_figure_spec).
|
|
121
126
|
- **글꼴**
|
|
122
127
|
- 한글 파일은 함초롬돋움(한글 기본 글꼴), PowerPoint 파일은 맑은 고딕(한국어 윈도 기본)을 씁니다.
|
package/package.json
CHANGED
package/server.json
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
"title": "Geo Figure (지리 시험 지도·그래프)",
|
|
5
5
|
"description": "지리 시험용 지도·그래프를 실제 통계로, 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만든다.",
|
|
6
6
|
"repository": { "url": "https://github.com/skyblue3925-svg/geo-figure-mcp", "source": "github" },
|
|
7
|
-
"version": "0.2.
|
|
7
|
+
"version": "0.2.6",
|
|
8
8
|
"packages": [
|
|
9
9
|
{
|
|
10
10
|
"registryType": "npm",
|
|
11
11
|
"identifier": "geo-figure-mcp",
|
|
12
|
-
"version": "0.2.
|
|
12
|
+
"version": "0.2.6",
|
|
13
13
|
"transport": { "type": "stdio" },
|
|
14
14
|
"environmentVariables": [
|
|
15
15
|
{ "name": "GEO_FIGURE_OUT", "description": "만든 파일을 저장할 폴더 (기본: 문서/지리시험자료)", "isRequired": false, "isSecret": false }
|
package/src/data.js
CHANGED
|
@@ -75,15 +75,28 @@ export async function findData({ source, indicators = [], regions = [], year, ye
|
|
|
75
75
|
if (source === 'climate') {
|
|
76
76
|
// 지점 이름(평가원 기출 지점 한글 이름) · 관측소 영문 이름 · "위도,경도" → 가장 가까운 WMO 관측소의 1991~2020 평년값
|
|
77
77
|
if (!regions.length) throw new Error('지점을 주세요. 예: ["샌프란시스코","이르쿠츠크"] 또는 ["37.57,126.98"]. 기출 지점 목록은 list_exam_climate_spots');
|
|
78
|
-
|
|
78
|
+
const units = { temp: '℃', precip: 'mm' };
|
|
79
|
+
const requested = Object.keys(units).filter((name) => !indicators.length || indicators.includes(name));
|
|
80
|
+
const unknown = indicators.find((name) => !Object.hasOwn(units, name));
|
|
81
|
+
if (unknown !== undefined) throw new Error('없는 기후 지표: ' + unknown + '. 선택 가능: temp, precip');
|
|
82
|
+
const rows = regions.map(climateRow);
|
|
83
|
+
if (requested.length < Object.keys(units).length) {
|
|
84
|
+
for (const row of rows) row.values = Object.fromEntries(requested.map((name) => [name, row.values[name]]));
|
|
85
|
+
}
|
|
86
|
+
return { title: 'WMO 기후평년값 1991~2020', unit: requested.map((name) => units[name]).join(', '), cite: SOURCES.climate.cite, year: '1991~2020', rows, get citeAll() { return [...new Set(this.rows.map((r) => r.cite || SOURCES.climate.cite))].join('; '); } };
|
|
79
87
|
}
|
|
80
88
|
if (source === 'seoul-daytime') {
|
|
81
89
|
const d = load('seoul-daytime-2020.json');
|
|
90
|
+
const requested = new Set(indicators);
|
|
91
|
+
const unknown = indicators.find((name) => !d.columns.includes(name));
|
|
92
|
+
if (unknown !== undefined) throw new Error(`없는 서울 주간 인구 지표: ${unknown}. 선택 가능: ${d.columns.join(', ')}`);
|
|
93
|
+
const columns = d.columns.map((name, i) => [name, i])
|
|
94
|
+
.filter(([name]) => !requested.size || requested.has(name));
|
|
82
95
|
const pick = regions.length ? regions : Object.keys(d.rows).filter((k) => k !== '서울특별시');
|
|
83
96
|
return { title: '서울 자치구 상주·주간 인구', unit: '명, 지수', cite: SOURCES['seoul-daytime'].cite, year: '2020', rows: pick.map((n) => {
|
|
84
97
|
const v = d.rows[n];
|
|
85
98
|
if (!v) throw new Error(`없는 자치구: ${n}`);
|
|
86
|
-
return { id: n, name: n, values: Object.fromEntries(
|
|
99
|
+
return { id: n, name: n, values: Object.fromEntries(columns.map(([name, i]) => [name, v[i]])) };
|
|
87
100
|
}) };
|
|
88
101
|
}
|
|
89
102
|
if (source === 'kosis') return kosisData(arguments[0].kosis || {});
|
|
@@ -266,7 +279,7 @@ export function bundleList() {
|
|
|
266
279
|
try { return JSON.parse(fs.readFileSync(new URL('kosis/index.json', DATA), 'utf8')); } catch { return []; }
|
|
267
280
|
}
|
|
268
281
|
const DEFAULT_PICK = ['계', '합계', '총인구', '전체', '소계', '총계', '전국'];
|
|
269
|
-
// q: { key, items:[항목 이름], period, where:{ C1:'총인구' }, regionDim:'C2' }
|
|
282
|
+
// q: { key, items:[항목 이름], period, where:{ C1:'총인구' }, regionDim:'C2', within:['경기'], regions:['경기 화성시'] }
|
|
270
283
|
export function bundleData(q) {
|
|
271
284
|
let o;
|
|
272
285
|
try { o = JSON.parse(fs.readFileSync(new URL(`kosis/${q.key}.json`, DATA), 'utf8')); } catch { throw new Error(`내장 통계에 없는 이름: ${q.key}. list_bundled_data 로 목록을 보세요.`); }
|
|
@@ -329,7 +342,23 @@ export function bundleData(q) {
|
|
|
329
342
|
r.mapName = m;
|
|
330
343
|
}
|
|
331
344
|
} catch {}
|
|
332
|
-
|
|
345
|
+
// 시·도 소속과 중복 지명이 확정된 뒤 출력할 지역만 고른다.
|
|
346
|
+
const regionNames = new Set(q.regions);
|
|
347
|
+
const provinces = new Set(q.within);
|
|
348
|
+
const matchedRegions = new Set();
|
|
349
|
+
const matchedProvinces = new Set();
|
|
350
|
+
const selected = res.filter(({ name, mapName }) => {
|
|
351
|
+
const province = mapName?.includes(' ') ? mapName.split(' ', 1)[0] : null;
|
|
352
|
+
if (provinces.size && !provinces.has(province)) return false;
|
|
353
|
+
matchedProvinces.add(province);
|
|
354
|
+
const matches = [mapName, name].filter((key) => regionNames.has(key));
|
|
355
|
+
matches.forEach((key) => matchedRegions.add(key));
|
|
356
|
+
return !regionNames.size || matches.length > 0;
|
|
357
|
+
});
|
|
358
|
+
const missing = [...provinces].filter((name) => !matchedProvinces.has(name))
|
|
359
|
+
.concat([...regionNames].filter((name) => !matchedRegions.has(name)));
|
|
360
|
+
if (missing.length) throw new Error('선택한 표·기간·분류에 없는 지역: ' + missing.join(', '));
|
|
361
|
+
return { title: o.title, unit: o.units, cite: o.cite, year: period, fixed, rows: selected, mapEdition, note: `내장 KOSIS 자료(받은 날 ${o.retrieved}). 고정한 분류: ${JSON.stringify(fixed)}. 지도에는 mapName 과 map.edition='${mapEdition}' 을 쓴다(일반구는 null — 시 합계 행을 쓴다)` };
|
|
333
362
|
}
|
|
334
363
|
|
|
335
364
|
// 지도 지역 이름(시·도 짧은 이름, '시도 시군구') — 내장 자료와 이름 맞추기용
|
package/src/tools.js
CHANGED
|
@@ -30,7 +30,7 @@ const GUIDE = `
|
|
|
30
30
|
3. 만들기 전에 반드시 '계획 요약'을 보여 주고 교사의 "예"를 받는다:
|
|
31
31
|
지표·단위 / 기준 연도 / 지역과 기호(A~E 또는 (가)~(마)) / 가공(지수·비율·편차·반올림) / 기호 순서(무작위·북→남·서→동·지정) / 출력(PPTX·HWPX) / 출처 문구
|
|
32
32
|
4. 계획 요약과 함께 preview_figures 로 시안 그림을 보여 준다. 그림마다 기본 시안을 보여 주고, 기호를 비교할 때만 compareLabelStyles:true를 쓴다. 교사가 ‘예’라고 하면 make_figures로 만든다. 로컬에서 명세가 같으면 figures 대신 previewId를 쓴다. 파일 위치와 정답표를 알려 준다.
|
|
33
|
-
5.
|
|
33
|
+
5. 저장한 지도의 범례·기호는 preview_figures(saved)로 바꾼다. 그 밖의 수정은 open_figure_spec으로 설계도를 읽는다. 통계를 다시 찾지 않는다. 손으로 고칠 땐 그룹 해제(개체 풀기) 한 번이면 모든 도형이 따로 움직인다고 알려 준다.
|
|
34
34
|
|
|
35
35
|
[품질 규칙 — 교사 기준 + 경기도교육청 지리 문항 제작 자료]
|
|
36
36
|
- 흑백 인쇄로 구분돼야 한다: 색 대신 빗금·회색 농도(자동).
|
|
@@ -53,6 +53,7 @@ const INSTRUCTIONS = [
|
|
|
53
53
|
const PREVIEW_TTL_MS = 30 * 60 * 1000;
|
|
54
54
|
const MAX_PREVIEWS = 8;
|
|
55
55
|
const MAX_PREVIEW_SPEC_BYTES = 64 * 1024;
|
|
56
|
+
const MAX_SAVED_SPEC_BYTES = 512 * 1024;
|
|
56
57
|
const figureSpecs = z.array(z.object({ title: z.string().optional() }).passthrough());
|
|
57
58
|
const figureStyle = z.object({ font: z.string().optional(), fontPptx: z.string().optional(), size: z.number().optional(), small: z.number().optional(), width: z.number().optional() });
|
|
58
59
|
const LABEL_NAMES = { halo: '① 흰 테두리(기본)', plain: '② 바탕 없음', box: '③ 네모 흰 바탕', circle: '④ 작은 원 흰 바탕' };
|
|
@@ -62,6 +63,48 @@ const withLabelStyle = (f, labelStyle) => {
|
|
|
62
63
|
return f.parts ? { ...f, parts: f.parts.map(apply) } : apply(f);
|
|
63
64
|
};
|
|
64
65
|
|
|
66
|
+
const savedEdit = z.strictObject({
|
|
67
|
+
name: z.string().min(1).optional().describe('기본 저장 폴더의 정확한 파일 이름, 확장자 제외'),
|
|
68
|
+
path: z.string().min(1).optional().describe('설계도 파일 경로(.geo-figure.json)'),
|
|
69
|
+
figure: z.number().int().positive().optional().describe('그림 번호(1부터), 그림이 여러 개면 필수'),
|
|
70
|
+
part: z.number().int().positive().optional().describe('자료 번호(1부터), 그림에 지도가 여러 개면 필수'),
|
|
71
|
+
legend: z.array(z.string()).max(6).optional().describe('범례 문구를 단계 순서대로 지정. []로 삭제'),
|
|
72
|
+
labelStyle: z.enum(['halo', 'plain', 'box', 'circle']).optional(),
|
|
73
|
+
labels: z.record(z.string(), z.string().min(1)).optional().describe('기존 지도 지역명에서 새 기호로 바꿀 항목만 지정'),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
function editSavedMap(edit) {
|
|
77
|
+
const { name, path: file, figure, part, legend, labelStyle, labels } = edit;
|
|
78
|
+
if ((name === undefined) === (file === undefined)) throw new Error('name 또는 path 하나를 지정하세요.');
|
|
79
|
+
if (name && (path.basename(name) !== name || /[\\/:]/.test(name) || name === '.' || name === '..')) throw new Error('name은 확장자 없는 파일 이름만 지정하세요.');
|
|
80
|
+
const source = file || path.join(OUT, name + '.geo-figure.json');
|
|
81
|
+
if (!source.endsWith('.geo-figure.json')) throw new Error('.geo-figure.json 설계도 파일을 지정하세요.');
|
|
82
|
+
if (fs.statSync(source).size > MAX_SAVED_SPEC_BYTES) throw new Error('저장된 설계도가 너무 큽니다. open_figure_spec으로 수정하세요.');
|
|
83
|
+
if (legend === undefined && labelStyle === undefined && !Object.keys(labels || {}).length) throw new Error('범례 또는 기호 변경을 지정하세요.');
|
|
84
|
+
const saved = JSON.parse(fs.readFileSync(source, 'utf8'));
|
|
85
|
+
const figures = figureSpecs.min(1).parse(saved.figures);
|
|
86
|
+
const style = figureStyle.optional().parse(saved.style);
|
|
87
|
+
if (!figure && figures.length !== 1) throw new Error('수정할 그림 번호(figure)를 지정하세요.');
|
|
88
|
+
const index = (figure || 1) - 1;
|
|
89
|
+
const target = figures[index];
|
|
90
|
+
if (!target) throw new Error('해당 그림 번호가 없습니다.');
|
|
91
|
+
const parts = target.parts || [target];
|
|
92
|
+
const mapIndexes = parts.flatMap((item, i) => item.map && item.map.type !== 'contour' ? [i] : []);
|
|
93
|
+
if (!part && mapIndexes.length !== 1) throw new Error('수정할 행정·세계 지도 자료 번호(part)를 지정하세요.');
|
|
94
|
+
const partIndex = part ? part - 1 : mapIndexes[0];
|
|
95
|
+
if (!mapIndexes.includes(partIndex)) throw new Error('해당 자료에 수정 가능한 지도가 없습니다.');
|
|
96
|
+
const map = parts[partIndex].map;
|
|
97
|
+
const unknown = Object.keys(labels || {}).find((key) => !Object.hasOwn(map.labels || {}, key));
|
|
98
|
+
if (unknown !== undefined) throw new Error('지도에 기존 기호가 없는 지역: ' + unknown);
|
|
99
|
+
const changed = { ...parts[partIndex], map: { ...map,
|
|
100
|
+
...(legend !== undefined ? { legend } : {}),
|
|
101
|
+
...(labelStyle !== undefined ? { labelStyle } : {}),
|
|
102
|
+
...(labels ? { labels: { ...map.labels, ...labels } } : {}),
|
|
103
|
+
} };
|
|
104
|
+
figures[index] = target.parts ? { ...target, parts: parts.map((item, i) => i === partIndex ? changed : item) } : changed;
|
|
105
|
+
return { figures, style, index };
|
|
106
|
+
}
|
|
107
|
+
|
|
65
108
|
export function createServer({ remote = false, publish = null } = {}) {
|
|
66
109
|
const server = new McpServer({ name: 'geo-figure-mcp', version: PKG_VERSION }, { instructions: INSTRUCTIONS });
|
|
67
110
|
const previews = new Map();
|
|
@@ -71,28 +114,44 @@ const wrap = (fn) => async (a) => { try { return ok(await fn(a)); } catch (e) {
|
|
|
71
114
|
|
|
72
115
|
server.tool('guide', '필요할 때 제작 순서(workflow) 또는 그림 명세(spec)를 조회한다. 인자 없이 호출하면 둘 다 반환한다.', {
|
|
73
116
|
topic: z.enum(['workflow', 'spec']).optional(),
|
|
74
|
-
|
|
117
|
+
section: z.enum(['map', 'chart', 'terrain']).optional().describe('topic:spec에서 필요한 명세만 선택'),
|
|
118
|
+
}, wrap(({ topic, section }) => [
|
|
75
119
|
updateNotice(),
|
|
76
120
|
'geo-figure-mcp ' + PKG_VERSION,
|
|
77
121
|
topic !== 'spec' && GUIDE,
|
|
78
|
-
topic !== 'workflow' &&
|
|
122
|
+
topic !== 'workflow' && (SPEC_INTRO + (section ? SPEC_SECTIONS[section] : Object.values(SPEC_SECTIONS).join(''))),
|
|
79
123
|
].filter(Boolean).join('\n')));
|
|
80
124
|
|
|
81
125
|
server.tool('list_sources', '쓸 수 있는 통계 자료원과 지표 예시를 보여 준다.', {}, wrap(() => SOURCES));
|
|
82
126
|
|
|
83
127
|
server.tool('find_data', '실제 통계를 찾는다. 결과에 출처(cite)와 연도가 붙는다. 숫자를 지어내지 말고 이 결과만 쓴다.', {
|
|
84
128
|
source: z.enum(remote ? Object.keys(SOURCES).filter((k) => k !== 'kosis') : Object.keys(SOURCES)).describe(remote ? '자료원 (원격 서버에서는 KOSIS 직접 조회를 쓰지 않는다 — 내장 자료 bundle 을 쓴다)' : '자료원'),
|
|
85
|
-
indicators: z.array(z.string()).default([]).describe('지표 코드 또는 열
|
|
129
|
+
indicators: z.array(z.string()).default([]).describe('지표 코드 또는 열 이름. 서울: 주간인구지수 등. 기후: temp(기온), precip(강수량). 서울·기후는 비우면 전체'),
|
|
86
130
|
regions: z.array(z.string()).default([]).describe('나라 ISO3(KOR, JPN…, 세계=WLD) / 기후: 기출 지점 한글 이름·관측소 영문 이름·"위도,경도" / 서울 자치구 이름'),
|
|
87
131
|
kosis: z.object({ orgId: z.string().optional(), tblId: z.string().optional(), itmId: z.string().optional(), objL1: z.string().optional(), objL2: z.string().optional(), year: z.number().optional() }).passthrough().optional().describe('source 가 kosis 일 때: { orgId, tblId, itmId, objL1:"ALL", objL2, year }'),
|
|
88
|
-
bundle: z.object({
|
|
132
|
+
bundle: z.object({
|
|
133
|
+
key: z.string(),
|
|
134
|
+
items: z.array(z.string()).optional().describe('필요한 항목 이름'),
|
|
135
|
+
within: z.array(z.string()).optional().describe('선택한 시·도의 지도에 표시할 시·군·구만 반환. 예: ["경기"]'),
|
|
136
|
+
regions: z.array(z.string()).optional().describe('필요한 지역의 mapName 또는 통계표 지역명'),
|
|
137
|
+
period: z.coerce.string().optional(),
|
|
138
|
+
where: z.object({}).passthrough().optional(),
|
|
139
|
+
}).passthrough().optional().describe('source가 bundle일 때 사용. 지도와 그래프에 필요한 항목과 지역만 요청한다.'),
|
|
89
140
|
year: z.number().optional().describe('특정 연도. 비우면 가장 최근'),
|
|
90
141
|
years: z.boolean().optional().describe('true 면 연도별 전체(시계열)'),
|
|
91
142
|
}, wrap((a) => { if (remote && a.source === 'kosis') throw new Error('원격 서버에서는 KOSIS 직접 조회를 하지 않습니다(인증키를 대화창에 넣지 않도록). list_bundled_data 의 내장 자료를 쓰거나, 내 컴퓨터에 설치해 쓰세요.'); return findData(a); }));
|
|
92
143
|
|
|
93
|
-
server.tool('list_exam_climate_spots', '평가원 기후 기출
|
|
144
|
+
server.tool('list_exam_climate_spots', '평가원 기후 기출 지점. 후보 이름과 기후 기호만 필요하면 summary:true를 쓴다.', {
|
|
94
145
|
code: z.string().optional().describe("기후 기호로 거르기. 예: 'Cs', 'BW', 'Df'"),
|
|
95
|
-
|
|
146
|
+
query: z.string().optional().describe('지점 이름의 일부'),
|
|
147
|
+
summary: z.boolean().optional().describe('지점 이름과 기후 기호만 반환'),
|
|
148
|
+
}, wrap(({ code, query, summary }) => {
|
|
149
|
+
const term = query?.trim() || '';
|
|
150
|
+
const spots = examSpots().filter((s) => s.name.includes(term) && (!code || (s.code || '').startsWith(code)));
|
|
151
|
+
return spots.map((s) => summary
|
|
152
|
+
? { name: s.name, code: s.code }
|
|
153
|
+
: { name: s.name, code: s.code, exams: s.exams, lat: s.lat, lon: s.lon, data: s.climate ? s.climate.source : (s.lat == null ? '좌표 없음' : 'WMO') });
|
|
154
|
+
}));
|
|
96
155
|
|
|
97
156
|
server.tool('list_bundled_data', '내장 KOSIS 통계 목록. query로 찾고 summary:true로 키와 주제만 본다. 선택한 키로 다시 조회하면 항목과 기간을 볼 수 있다.', {
|
|
98
157
|
query: z.string().optional().describe('표 키 또는 검색어'),
|
|
@@ -122,7 +181,13 @@ server.tool('list_regions', '지도에 쓸 수 있는 지역 이름 목록(한
|
|
|
122
181
|
region: z.enum(['korea', 'world']).default('korea'),
|
|
123
182
|
level: z.enum(['sido', 'sigungu']).default('sido'),
|
|
124
183
|
within: z.array(z.string()).optional().describe("시·군·구 목록을 이 시·도 안으로 좁힌다. 예: ['경기']"),
|
|
125
|
-
|
|
184
|
+
edition: z.enum(['2025', '2026']).optional().describe('한국 지도 판'),
|
|
185
|
+
query: z.string().optional().describe('찾을 지역 이름의 일부'),
|
|
186
|
+
}, wrap(({ query, ...args }) => {
|
|
187
|
+
const term = query?.trim().toLowerCase();
|
|
188
|
+
const names = listRegions(args);
|
|
189
|
+
return term ? names.filter((name) => name.toLowerCase().includes(term)) : names;
|
|
190
|
+
}));
|
|
126
191
|
|
|
127
192
|
server.tool('suggest_regions', '지표 값이 서로 뚜렷하게 갈리는 지역 k곳을 추천한다(판별이 잘 되는 조합).', {
|
|
128
193
|
rows: z.array(z.object({ name: z.string(), values: z.object({}).catchall(z.number()) })).describe('find_data 결과의 rows'),
|
|
@@ -190,29 +255,43 @@ server.tool('make_figures', '그림 명세로 PPTX·HWPX 파일을 만든다.
|
|
|
190
255
|
}));
|
|
191
256
|
|
|
192
257
|
server.tool('preview_figures', '파일을 만들기 전 PNG 시안을 보여 준다. 기호 비교가 필요하면 compareLabelStyles:true를 쓴다. 로컬 previewId는 make_figures에서 재사용할 수 있다.', {
|
|
193
|
-
figures: figureSpecs.describe('make_figures와 같은 그림 명세'),
|
|
258
|
+
figures: (remote ? figureSpecs : figureSpecs.optional()).describe('make_figures와 같은 그림 명세'),
|
|
259
|
+
...(remote ? {} : { saved: savedEdit.optional().describe('로컬 설계도에서 범례·기호만 수정. figures 대신 사용') }),
|
|
194
260
|
compareLabelStyles: z.boolean().optional().describe('true면 첫 지도에 기호 스타일 4개를 비교'),
|
|
195
261
|
style: figureStyle.optional(),
|
|
196
262
|
}, async (a) => {
|
|
197
263
|
try {
|
|
198
|
-
|
|
264
|
+
let { figures, style } = a;
|
|
265
|
+
let savedIndex;
|
|
266
|
+
if (a.saved) {
|
|
267
|
+
if (figures || style || a.compareLabelStyles) throw new Error('saved는 figures, style, 기호 비교와 함께 쓸 수 없습니다.');
|
|
268
|
+
({ figures, style, index: savedIndex } = editSavedMap(a.saved));
|
|
269
|
+
}
|
|
270
|
+
if (!figures) throw new Error('figures 또는 saved를 지정하세요.');
|
|
271
|
+
const st = { ...loadStyle(), ...style };
|
|
199
272
|
const content = [];
|
|
200
|
-
const compareIndex = a.compareLabelStyles &&
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
273
|
+
const compareIndex = a.compareLabelStyles && figures.length ? Math.max(0, figures.findIndex(hasMap)) : -1;
|
|
274
|
+
const caption = (f, i) => ({ cap: '시안 ' + (i + 1) + ': ' + (f.title || ''), spec: f });
|
|
275
|
+
const list = savedIndex !== undefined ? [caption(figures[savedIndex], savedIndex)] : compareIndex >= 0
|
|
276
|
+
? Object.entries(LABEL_NAMES).map(([label, cap]) => ({ cap, spec: withLabelStyle(figures[compareIndex], label) }))
|
|
277
|
+
: figures.slice(0, 6).map(caption);
|
|
204
278
|
for (const { cap, spec } of list) {
|
|
205
279
|
const fig = await makeFigure(spec, st);
|
|
206
280
|
content.push({ type: 'text', text: cap }, { type: 'image', mimeType: 'image/png', data: Buffer.from(renderPng(fig, { width: 800 })).toString('base64') });
|
|
207
281
|
}
|
|
208
282
|
let how = compareIndex >= 0 ? '기호 ①~④ 중 하나를 고르세요(halo·plain·box·circle).' : '교사 확인 후 파일을 만드세요.';
|
|
209
|
-
const allFiguresShown = compareIndex >= 0 ?
|
|
210
|
-
|
|
283
|
+
const allFiguresShown = compareIndex >= 0 ? figures.length === 1 : list.length === figures.length;
|
|
284
|
+
const maxBytes = a.saved ? MAX_SAVED_SPEC_BYTES : MAX_PREVIEW_SPEC_BYTES;
|
|
285
|
+
const canReuse = Buffer.byteLength(JSON.stringify({ figures, style })) <= maxBytes;
|
|
286
|
+
if (a.saved && !canReuse) throw new Error('수정된 설계도가 너무 큽니다. open_figure_spec으로 수정하세요.');
|
|
287
|
+
if (!remote && list.length && (a.saved || allFiguresShown) && canReuse) {
|
|
211
288
|
const id = randomBytes(8).toString('hex');
|
|
212
289
|
if (previews.size >= MAX_PREVIEWS) previews.delete(previews.keys().next().value);
|
|
213
|
-
previews.set(id, { figures
|
|
290
|
+
previews.set(id, { figures, style, st, compareIndex, expires: Date.now() + PREVIEW_TTL_MS });
|
|
214
291
|
how += '\npreviewId: ' + id + '\nmake_figures에 figures 대신 이 ID를 보내세요.';
|
|
215
292
|
if (compareIndex >= 0) how += ' 선택한 labelStyle도 보내세요.';
|
|
293
|
+
if (a.saved) how += ' 저장할 때 새 파일 이름과 출력 형식을 지정하세요.';
|
|
294
|
+
if (a.saved?.labels) how += ' 지도 기호만 바뀝니다. 그래프 기호와 정답표를 확인하세요.';
|
|
216
295
|
} else {
|
|
217
296
|
how += ' make_figures에 figures를 보내세요.';
|
|
218
297
|
}
|
|
@@ -243,11 +322,13 @@ server.tool('set_style', '학교 양식에 맞춘 글꼴·크기·그림 폭을
|
|
|
243
322
|
width: z.number().optional().describe('그림 기본 폭 mm(기본 82.5 = 2단 시험지 한 단)'),
|
|
244
323
|
}, wrap((a) => (remote ? '원격 서버에서는 설정을 저장하지 않습니다. 학교 양식은 make_figures 의 style 로 매번 넘기세요.' : saveStyle(Object.fromEntries(Object.entries(a).filter(([, v]) => v != null))))));
|
|
245
324
|
|
|
246
|
-
const
|
|
325
|
+
const SPEC_INTRO = `
|
|
247
326
|
[그림 명세(spec)]
|
|
248
327
|
{ title, layout:'row'|'column', source:'출처 문구', notes:['* 주석'], parts:[ { caption:'(가)', map:{…} } , { caption:'(나)', chart:{…} } ] }
|
|
249
328
|
- 한 부분만이면 parts 없이 { title, map } 또는 { title, chart } 도 된다.
|
|
250
|
-
|
|
329
|
+
`;
|
|
330
|
+
const SPEC_SECTIONS = {
|
|
331
|
+
map: `
|
|
251
332
|
map:
|
|
252
333
|
{ region:'korea'|'world', level:'sido'|'sigungu', within:['서울'], bbox:[서경,남위,동경,북위], detail:'high'|'mid'|'low', width:mm,
|
|
253
334
|
classes:{ '경북':1, '서울 종로구':3 } // 단계 번호 0~5 (흰색→빗금→연회색→격자→회색→진회색)
|
|
@@ -257,8 +338,9 @@ map:
|
|
|
257
338
|
points:[{ lon, lat, label:'A' }], // 점 + 기호 (도시·기후 지점)
|
|
258
339
|
flows:[{ from:'경기', to:'서울', value:120 }], // 흐름 화살표(굵기 = 값)
|
|
259
340
|
graticule:20, scaleBar:true|false, edition:'2026'|'2025' }
|
|
260
|
-
- 시·군·구 이름은 '서울 종로구'처럼 '시·도 짧은이름 + 이름'. list_regions
|
|
261
|
-
|
|
341
|
+
- 시·군·구 이름은 '서울 종로구'처럼 '시·도 짧은이름 + 이름'. 필요할 때 list_regions에 query와 edition으로 확인.
|
|
342
|
+
`,
|
|
343
|
+
chart: `
|
|
262
344
|
chart: type = ${Object.keys(CHARTS).join(' | ')} | profile | landform
|
|
263
345
|
- bar/stacked: { categories:[…], series:[{name, values:[…]}], unit:'(%)', valueLabels:'none'|'last'|'all', width, height }
|
|
264
346
|
- scatter/bubble: { points:[{label:'A', x, y, size?}], xLabel, yLabel, sizeLabel }
|
|
@@ -266,12 +348,14 @@ chart: type = ${Object.keys(CHARTS).join(' | ')} | profile | landform
|
|
|
266
348
|
- deviation: { categories, series:[{name, values}], base:'기준 이름', unit }
|
|
267
349
|
- pyramid: { groups:['0~4',…], male:[%], female:[%], unit:'%' }
|
|
268
350
|
- triangle: { points:[{label, a, b, c}], names:['1차','2차','3차'], unit:'%' }
|
|
269
|
-
|
|
351
|
+
`,
|
|
352
|
+
terrain: `- profile(지형 단면, 실제 표고): { from:[위도,경도], to:[위도,경도], labels:[{km, label:'A'}], vex } — 또는 points:[[km,m]…]
|
|
270
353
|
- landform(교과서식 모식도): { preset, labels:{ 부분이름:'A' } } — preset 과 부분: ${Object.entries(LANDFORM_PRESETS).map(([k, v]) => `${k}(${v.title}: ${v.parts.join('·')})`).join(' / ')}
|
|
271
354
|
|
|
272
355
|
map type 'contour'(등고선 지형도, 실제 표고): { type:'contour', bbox:[서경,남위,동경,북위], interval:m, index:5, points:[{lon,lat,label}], line:[[위도,경도],[위도,경도]](단면선), resolution:70 }
|
|
273
356
|
- 좁은 범위(가로 0.05~0.5°)가 알맞다. 표고는 Terrain Tiles(약 30m, 원자료 SRTM 등)라 아주 작은 지형(사구 등)은 안 보인다.
|
|
274
|
-
|
|
357
|
+
`,
|
|
358
|
+
};
|
|
275
359
|
|
|
276
360
|
return server;
|
|
277
361
|
}
|