@egdesk/next-api-plugin 1.5.3 → 1.5.5

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.
@@ -8,6 +8,118 @@ import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
  import * as os from 'os';
10
10
 
11
+ /** Columns auto-managed by EGDesk — omit from committed seed schema. */
12
+ const SYSTEM_SCHEMA_COLUMNS = new Set(['id', 'imported_at']);
13
+
14
+ export interface SchemaTableDefinition {
15
+ tableName: string;
16
+ displayName: string;
17
+ columns: string[];
18
+ }
19
+
20
+ function escapeTsString(value: string): string {
21
+ return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
22
+ }
23
+
24
+ function schemaKeyForTable(tableName: string): string {
25
+ const key = tableName.replace(/[^a-zA-Z0-9_]/g, '_');
26
+ return /^[a-zA-Z_]/.test(key) ? key : `_${key}`;
27
+ }
28
+
29
+ /**
30
+ * Format egdesk.schema.ts content — the committed, portable seed schema.
31
+ */
32
+ export function formatEgdeskSchemaFileContent(tables: SchemaTableDefinition[]): string {
33
+ const tableEntries =
34
+ tables.length === 0
35
+ ? ` // example_table: {
36
+ // name: 'example_table',
37
+ // displayName: 'Example Table',
38
+ // columns: ['name', 'created_at'],
39
+ // columnCount: 2,
40
+ // rowCount: 0,
41
+ // },`
42
+ : tables
43
+ .map((table) => {
44
+ const key = schemaKeyForTable(table.tableName);
45
+ const userColumns = table.columns.filter((col) => !SYSTEM_SCHEMA_COLUMNS.has(col));
46
+ const columns = userColumns.map((col) => `'${escapeTsString(col)}'`).join(', ');
47
+ return ` ${key}: {
48
+ name: '${escapeTsString(table.tableName)}',
49
+ displayName: '${escapeTsString(table.displayName)}',
50
+ columns: [${columns}],
51
+ columnCount: ${userColumns.length},
52
+ rowCount: 0,
53
+ }`;
54
+ })
55
+ .join(',\n');
56
+
57
+ return `/**
58
+ * egdesk.schema.ts — committed seed schema
59
+ *
60
+ * COMMIT THIS FILE TO GIT.
61
+ *
62
+ * When someone opens this project in their EGDesk, these tables are created
63
+ * automatically in their dev database on first server start.
64
+ *
65
+ * Unlike egdesk.config.ts (auto-generated, gitignored), this file is the
66
+ * portable source of truth for your app's database structure.
67
+ *
68
+ * Edit this file when you add/remove tables or columns. Do NOT edit
69
+ * egdesk.config.ts — EGDesk regenerates it from the live database.
70
+ */
71
+
72
+ export const TABLES = {
73
+ ${tableEntries}
74
+ } as const;
75
+
76
+ export type TableName = keyof typeof TABLES;
77
+ export const TABLE_NAMES = Object.keys(TABLES) as TableName[];
78
+ `;
79
+ }
80
+
81
+ /**
82
+ * Write egdesk.schema.ts to the project root.
83
+ */
84
+ export function generateSchemaFile(projectPath: string, tables: SchemaTableDefinition[]): void {
85
+ const schemaPath = path.join(projectPath, 'egdesk.schema.ts');
86
+ fs.writeFileSync(schemaPath, formatEgdeskSchemaFileContent(tables).replace(/\r?\n/g, os.EOL), 'utf-8');
87
+ console.log(`✅ Generated ${schemaPath}`);
88
+ }
89
+
90
+ export type EnsureSchemaFileResult = {
91
+ created: boolean;
92
+ source: 'existing' | 'database' | 'template';
93
+ tableCount: number;
94
+ };
95
+
96
+ /**
97
+ * Create egdesk.schema.ts only when missing. Never overwrites an existing file.
98
+ */
99
+ export function ensureSchemaFile(
100
+ projectPath: string,
101
+ tables: SchemaTableDefinition[],
102
+ ): EnsureSchemaFileResult {
103
+ const schemaPath = path.join(projectPath, 'egdesk.schema.ts');
104
+ if (fs.existsSync(schemaPath)) {
105
+ return { created: false, source: 'existing', tableCount: tables.length };
106
+ }
107
+
108
+ const userTables = tables
109
+ .map((table) => ({
110
+ ...table,
111
+ columns: table.columns.filter((col) => !SYSTEM_SCHEMA_COLUMNS.has(col)),
112
+ }))
113
+ .filter((table) => table.columns.length > 0);
114
+
115
+ generateSchemaFile(projectPath, userTables);
116
+ return {
117
+ created: true,
118
+ source: userTables.length > 0 ? 'database' : 'template',
119
+ tableCount: userTables.length,
120
+ };
121
+ }
122
+
11
123
  /**
12
124
  * Generate egdesk-helpers.ts file
13
125
  */
@@ -18,14 +130,70 @@ export function generateHelpers(projectPath: string): void {
18
130
  * EGDesk Helper Functions for Next.js
19
131
  *
20
132
  * Type-safe helpers for EGDesk user data, FinanceHub (banks, cards, Hometax, promissory notes),
21
- * internal knowledge / business identity / company research (MCP), and browser recorder replay.
133
+ * internal knowledge / business identity / company research (MCP), Korean law (MCP), and browser recorder replay.
22
134
  * Works in both client and server components.
23
135
  *
24
- * Generated by @egdesk/next-api-plugin
136
+ * Generated by @egdesk/next-api-plugin — do not edit by hand.
137
+ *
138
+ * Schema files:
139
+ * - egdesk.schema.ts — committed seed schema (edit this; commit to git)
140
+ * - egdesk.config.ts — auto-generated runtime snapshot (gitignored; do not edit)
25
141
  */
26
142
 
27
143
  import { EGDESK_CONFIG } from './egdesk.config';
28
144
 
145
+ /**
146
+ * Resolve EGDesk tunnel basePath for client-side fetch.
147
+ * Next.js basePath does NOT apply to raw fetch() — prepend manually in production.
148
+ */
149
+ export function getEgdeskBasePath(): string {
150
+ if (typeof window === 'undefined') {
151
+ return (
152
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) ||
153
+ (typeof process !== 'undefined' && process.env?.EGDESK_BASE_PATH) ||
154
+ ''
155
+ );
156
+ }
157
+
158
+ const fromEnv =
159
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) || '';
160
+ if (fromEnv) return fromEnv;
161
+
162
+ // Fallback: detect /t/{tunnelId}/p/{projectName} from the current URL
163
+ const parts = window.location.pathname.split('/').filter(Boolean);
164
+ if (parts[0] === 't' && parts.length >= 4 && parts[2] === 'p') {
165
+ return \`/\${parts.slice(0, 4).join('/')}\`;
166
+ }
167
+ return '';
168
+ }
169
+
170
+ /**
171
+ * Fetch wrapper that prepends EGDesk basePath to relative URLs.
172
+ * Use for /api/* routes and /__*_proxy paths in client components.
173
+ */
174
+ export async function apiFetch(path: string, options?: RequestInit): Promise<Response> {
175
+ const basePath = getEgdeskBasePath();
176
+ const url =
177
+ path.startsWith('/') && !path.startsWith('//') ? \`\${basePath}\${path}\` : path;
178
+ return fetch(url, options);
179
+ }
180
+
181
+ /** Build EGDesk routing headers (project-id + env) for server-side direct calls. */
182
+ function buildServerEgdeskHeaders(): Record<string, string> {
183
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
184
+ const apiKey =
185
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
186
+ EGDESK_CONFIG.apiKey;
187
+ const projectId =
188
+ typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_EGDESK_PROJECT_ID : undefined;
189
+ const egdeskEnv =
190
+ typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_EGDESK_ENV : undefined;
191
+ if (apiKey) headers['X-Api-Key'] = apiKey;
192
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
193
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
194
+ return headers;
195
+ }
196
+
29
197
  /**
30
198
  * Parse EGDesk MCP \`/tools/call\` JSON so \`error\` is shown even when HTTP status is 500.
31
199
  */
@@ -78,9 +246,6 @@ export async function callUserDataTool(
78
246
  args: Record<string, any> = {}
79
247
  ): Promise<any> {
80
248
  const body = JSON.stringify({ tool: toolName, arguments: args });
81
- const headers: Record<string, string> = {
82
- 'Content-Type': 'application/json'
83
- };
84
249
 
85
250
  const isServer = typeof window === 'undefined';
86
251
 
@@ -90,22 +255,16 @@ export async function callUserDataTool(
90
255
  const apiUrl =
91
256
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
92
257
  EGDESK_CONFIG.apiUrl;
93
- const apiKey =
94
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
95
- EGDESK_CONFIG.apiKey;
96
- if (apiKey) {
97
- headers['X-Api-Key'] = apiKey;
98
- }
99
258
  response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
100
259
  method: 'POST',
101
- headers,
260
+ headers: buildServerEgdeskHeaders(),
102
261
  body
103
262
  });
104
263
  } else {
105
- // Browser: use proxy for CORS and tunnel base path
106
- response = await fetch('/__user_data_proxy', {
264
+ // Browser: use proxy for CORS and tunnel base path (proxy.ts injects routing headers)
265
+ response = await apiFetch('/__user_data_proxy', {
107
266
  method: 'POST',
108
- headers,
267
+ headers: { 'Content-Type': 'application/json' },
109
268
  body
110
269
  });
111
270
  }
@@ -168,12 +327,49 @@ export async function aggregateTable(
168
327
  }
169
328
 
170
329
  /**
171
- * Execute raw SQL query (read-only, SELECT only)
330
+ * Execute raw SQL query (read-only, SELECT only).
331
+ * Supports JOINs — use listTables() and getTableSchema() to discover tables/columns first.
332
+ * For structured multi-table joins, prefer joinTables().
172
333
  */
173
334
  export async function executeSQL(query: string) {
174
335
  return callUserDataTool('user_data_sql_query', { query });
175
336
  }
176
337
 
338
+ /**
339
+ * Join one or more tables and query combined rows.
340
+ * Use listTables() and getTableSchema() first to discover table names and columns.
341
+ *
342
+ * @example
343
+ * await joinTables('orders', [
344
+ * { table: 'customers', on: { leftColumn: 'customer_id', rightColumn: 'id' } },
345
+ * { table: 'products', on: { leftColumn: 'orders.product_id', rightColumn: 'id' }, joinType: 'LEFT' },
346
+ * ]);
347
+ */
348
+ export async function joinTables(
349
+ fromTable: string,
350
+ joins: Array<{
351
+ table: string;
352
+ on:
353
+ | { leftColumn: string; rightColumn: string }
354
+ | Array<{ leftColumn: string; rightColumn: string }>;
355
+ joinType?: 'INNER' | 'LEFT' | 'RIGHT';
356
+ }>,
357
+ options: {
358
+ select?: string[];
359
+ filters?: Record<string, string>;
360
+ limit?: number;
361
+ offset?: number;
362
+ orderBy?: string;
363
+ orderDirection?: 'ASC' | 'DESC';
364
+ } = {}
365
+ ) {
366
+ return callUserDataTool('user_data_join', {
367
+ fromTable,
368
+ joins,
369
+ ...options
370
+ });
371
+ }
372
+
177
373
  /**
178
374
  * List all available tables
179
375
  */
@@ -294,9 +490,6 @@ export async function callFinanceHubTool(
294
490
  args: Record<string, any> = {}
295
491
  ): Promise<any> {
296
492
  const body = JSON.stringify({ tool: toolName, arguments: args });
297
- const headers: Record<string, string> = {
298
- 'Content-Type': 'application/json'
299
- };
300
493
 
301
494
  const isServer = typeof window === 'undefined';
302
495
 
@@ -305,21 +498,15 @@ export async function callFinanceHubTool(
305
498
  const apiUrl =
306
499
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
307
500
  EGDESK_CONFIG.apiUrl;
308
- const apiKey =
309
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
310
- EGDESK_CONFIG.apiKey;
311
- if (apiKey) {
312
- headers['X-Api-Key'] = apiKey;
313
- }
314
501
  response = await fetch(\`\${apiUrl}/financehub/tools/call\`, {
315
502
  method: 'POST',
316
- headers,
503
+ headers: buildServerEgdeskHeaders(),
317
504
  body
318
505
  });
319
506
  } else {
320
- response = await fetch('/__financehub_proxy', {
507
+ response = await apiFetch('/__financehub_proxy', {
321
508
  method: 'POST',
322
- headers,
509
+ headers: { 'Content-Type': 'application/json' },
323
510
  body
324
511
  });
325
512
  }
@@ -632,9 +819,6 @@ export async function callInternalKnowledgeTool(
632
819
  args: Record<string, any> = {}
633
820
  ): Promise<any> {
634
821
  const body = JSON.stringify({ tool: toolName, arguments: args });
635
- const headers: Record<string, string> = {
636
- 'Content-Type': 'application/json'
637
- };
638
822
 
639
823
  const isServer = typeof window === 'undefined';
640
824
 
@@ -643,21 +827,15 @@ export async function callInternalKnowledgeTool(
643
827
  const apiUrl =
644
828
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
645
829
  EGDESK_CONFIG.apiUrl;
646
- const apiKey =
647
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
648
- EGDESK_CONFIG.apiKey;
649
- if (apiKey) {
650
- headers['X-Api-Key'] = apiKey;
651
- }
652
830
  response = await fetch(\`\${apiUrl}/internal-knowledge/tools/call\`, {
653
831
  method: 'POST',
654
- headers,
832
+ headers: buildServerEgdeskHeaders(),
655
833
  body
656
834
  });
657
835
  } else {
658
- response = await fetch('/__internal_knowledge_proxy', {
836
+ response = await apiFetch('/__internal_knowledge_proxy', {
659
837
  method: 'POST',
660
- headers,
838
+ headers: { 'Content-Type': 'application/json' },
661
839
  body
662
840
  });
663
841
  }
@@ -752,28 +930,76 @@ export async function getBusinessIdentityServicesProducts(snapshotId: string) {
752
930
  return callInternalKnowledgeTool('businessidentity_get_services_products', { snapshotId });
753
931
  }
754
932
 
933
+ /**
934
+ * Call EGDesk Company Research MCP tool (run workflows and query saved research).
935
+ *
936
+ * - Server: \`POST {apiUrl}/company-research/tools/call\`
937
+ * - Client: \`POST /__company_research_proxy\` (see proxy.ts / middleware)
938
+ */
939
+ export async function callCompanyResearchTool(
940
+ toolName: string,
941
+ args: Record<string, any> = {}
942
+ ): Promise<any> {
943
+ const body = JSON.stringify({ tool: toolName, arguments: args });
944
+
945
+ const isServer = typeof window === 'undefined';
946
+
947
+ let response: Response;
948
+ if (isServer) {
949
+ const apiUrl =
950
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
951
+ EGDESK_CONFIG.apiUrl;
952
+ response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
953
+ method: 'POST',
954
+ headers: buildServerEgdeskHeaders(),
955
+ body
956
+ });
957
+ } else {
958
+ response = await apiFetch('/__company_research_proxy', {
959
+ method: 'POST',
960
+ headers: { 'Content-Type': 'application/json' },
961
+ body
962
+ });
963
+ }
964
+
965
+ return parseEgdeskMcpToolResponse(response);
966
+ }
967
+
968
+ /** Run full company research workflow for a domain (several minutes) */
969
+ export async function runCompanyResearch(
970
+ domain: string,
971
+ options: { bypassCache?: boolean; inquiryData?: Record<string, any> } = {}
972
+ ) {
973
+ return callCompanyResearchTool('companyresearch_run', { domain, ...options });
974
+ }
975
+
755
976
  /** List company research records */
756
977
  export async function listCompanyResearch(
757
978
  status?: 'completed' | 'failed' | 'in_progress'
758
979
  ) {
759
- return callInternalKnowledgeTool('companyresearch_list_all', {
980
+ return callCompanyResearchTool('companyresearch_list_all', {
760
981
  ...(status != null ? { status } : {})
761
982
  });
762
983
  }
763
984
 
764
985
  /** One company research record by ID */
765
986
  export async function getCompanyResearchById(researchId: string) {
766
- return callInternalKnowledgeTool('companyresearch_get_by_id', { researchId });
987
+ return callCompanyResearchTool('companyresearch_get_by_id', { researchId });
767
988
  }
768
989
 
769
990
  /** Research records for a domain */
770
991
  export async function getCompanyResearchByDomain(domain: string) {
771
- return callInternalKnowledgeTool('companyresearch_get_by_domain', { domain });
992
+ return callCompanyResearchTool('companyresearch_get_by_domain', { domain });
993
+ }
994
+
995
+ /** Most recent completed research for a domain */
996
+ export async function getLatestCompletedCompanyResearch(domain: string) {
997
+ return callCompanyResearchTool('companyresearch_get_latest_completed', { domain });
772
998
  }
773
999
 
774
1000
  /** Search company research by company name or domain */
775
1001
  export async function searchCompanyResearch(searchText: string) {
776
- return callInternalKnowledgeTool('companyresearch_search', { searchText });
1002
+ return callCompanyResearchTool('companyresearch_search', { searchText });
777
1003
  }
778
1004
 
779
1005
  // ==========================================
@@ -791,9 +1017,6 @@ export async function callBrowserRecordingTool(
791
1017
  args: Record<string, any> = {}
792
1018
  ): Promise<any> {
793
1019
  const body = JSON.stringify({ tool: toolName, arguments: args });
794
- const headers: Record<string, string> = {
795
- 'Content-Type': 'application/json'
796
- };
797
1020
 
798
1021
  const isServer = typeof window === 'undefined';
799
1022
 
@@ -802,21 +1025,15 @@ export async function callBrowserRecordingTool(
802
1025
  const apiUrl =
803
1026
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
804
1027
  EGDESK_CONFIG.apiUrl;
805
- const apiKey =
806
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
807
- EGDESK_CONFIG.apiKey;
808
- if (apiKey) {
809
- headers['X-Api-Key'] = apiKey;
810
- }
811
1028
  response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
812
1029
  method: 'POST',
813
- headers,
1030
+ headers: buildServerEgdeskHeaders(),
814
1031
  body
815
1032
  });
816
1033
  } else {
817
- response = await fetch('/__browser_recording_proxy', {
1034
+ response = await apiFetch('/__browser_recording_proxy', {
818
1035
  method: 'POST',
819
- headers,
1036
+ headers: { 'Content-Type': 'application/json' },
820
1037
  body
821
1038
  });
822
1039
  }
@@ -893,6 +1110,16 @@ export async function removeBrowserRecordingSchedule(testFile: string) {
893
1110
  return callBrowserRecordingTool('browser_recording_remove_schedule', { testFile });
894
1111
  }
895
1112
 
1113
+ /** Pause a recurring schedule without deleting it */
1114
+ export async function pauseBrowserRecordingSchedule(testFile: string) {
1115
+ return callBrowserRecordingTool('browser_recording_pause_schedule', { testFile });
1116
+ }
1117
+
1118
+ /** Resume a paused recurring schedule */
1119
+ export async function resumeBrowserRecordingSchedule(testFile: string) {
1120
+ return callBrowserRecordingTool('browser_recording_resume_schedule', { testFile });
1121
+ }
1122
+
896
1123
  export type BrowserRecordingSyncConfigOptions = {
897
1124
  testFile?: string;
898
1125
  scriptFolderPath?: string;
@@ -959,9 +1186,6 @@ export async function callAICenterTool(
959
1186
  args: Record<string, any> = {}
960
1187
  ): Promise<any> {
961
1188
  const body = JSON.stringify({ tool: toolName, arguments: args });
962
- const headers: Record<string, string> = {
963
- 'Content-Type': 'application/json'
964
- };
965
1189
 
966
1190
  const isServer = typeof window === 'undefined';
967
1191
 
@@ -970,21 +1194,15 @@ export async function callAICenterTool(
970
1194
  const apiUrl =
971
1195
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
972
1196
  EGDESK_CONFIG.apiUrl;
973
- const apiKey =
974
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
975
- EGDESK_CONFIG.apiKey;
976
- if (apiKey) {
977
- headers['X-Api-Key'] = apiKey;
978
- }
979
1197
  response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
980
1198
  method: 'POST',
981
- headers,
1199
+ headers: buildServerEgdeskHeaders(),
982
1200
  body
983
1201
  });
984
1202
  } else {
985
- response = await fetch('/__ai_center_proxy', {
1203
+ response = await apiFetch('/__ai_center_proxy', {
986
1204
  method: 'POST',
987
- headers,
1205
+ headers: { 'Content-Type': 'application/json' },
988
1206
  body
989
1207
  });
990
1208
  }
@@ -1228,6 +1446,382 @@ export async function getCalendarEventsFromAICenter() {
1228
1446
  export async function completeTask(taskId: string, status: 'completed' | 'approved' | 'rejected') {
1229
1447
  return callAICenterTool('ai_center_complete_task', { taskId, status });
1230
1448
  }
1449
+
1450
+ // ==========================================
1451
+ // KOREAN LAW / LAWYER (MCP)
1452
+ // ==========================================
1453
+
1454
+ /**
1455
+ * Call EGDesk Korean Law MCP tool (법제처 API — laws, precedents, admin rules, municipal ordinances).
1456
+ *
1457
+ * - Server: \`POST {apiUrl}/korean-law/tools/call\`
1458
+ * - Client: \`POST /__korean_law_proxy\` (see proxy.ts / middleware)
1459
+ */
1460
+ export async function callKoreanLawTool(
1461
+ toolName: string,
1462
+ args: Record<string, any> = {}
1463
+ ): Promise<any> {
1464
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1465
+
1466
+ const isServer = typeof window === 'undefined';
1467
+
1468
+ let response: Response;
1469
+ if (isServer) {
1470
+ const apiUrl =
1471
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1472
+ EGDESK_CONFIG.apiUrl;
1473
+ response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
1474
+ method: 'POST',
1475
+ headers: buildServerEgdeskHeaders(),
1476
+ body
1477
+ });
1478
+ } else {
1479
+ response = await apiFetch('/__korean_law_proxy', {
1480
+ method: 'POST',
1481
+ headers: { 'Content-Type': 'application/json' },
1482
+ body
1483
+ });
1484
+ }
1485
+
1486
+ return parseEgdeskMcpToolResponse(response);
1487
+ }
1488
+
1489
+ /** Search laws, precedents, administrative rules, or municipal ordinances */
1490
+ export async function searchKoreanLaw(
1491
+ query: string,
1492
+ options: {
1493
+ target?: 'law' | 'prec' | 'admrul' | 'ordin';
1494
+ display?: number;
1495
+ page?: number;
1496
+ } = {}
1497
+ ) {
1498
+ return callKoreanLawTool('korean_law_search', { query, ...options });
1499
+ }
1500
+
1501
+ /** Get full text of a law, administrative rule, or municipal ordinance */
1502
+ export async function getKoreanLawText(
1503
+ id: string,
1504
+ target: 'law' | 'admrul' | 'ordin' = 'law'
1505
+ ) {
1506
+ return callKoreanLawTool('korean_law_get_text', { id, target });
1507
+ }
1508
+
1509
+ /** Get full text of a court precedent (판례) */
1510
+ export async function getKoreanLawDecision(id: string) {
1511
+ return callKoreanLawTool('korean_law_get_decision', { id });
1512
+ }
1513
+
1514
+ // ==========================================
1515
+ // SEO (MCP)
1516
+ // ==========================================
1517
+
1518
+ /**
1519
+ * Call EGDesk SEO MCP tool (Lighthouse audits and report history).
1520
+ *
1521
+ * - Server: \`POST {apiUrl}/seo/tools/call\`
1522
+ * - Client: \`POST /__seo_proxy\` (see proxy.ts / middleware)
1523
+ */
1524
+ export async function callSeoTool(
1525
+ toolName: string,
1526
+ args: Record<string, any> = {}
1527
+ ): Promise<any> {
1528
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1529
+
1530
+ const isServer = typeof window === 'undefined';
1531
+
1532
+ let response: Response;
1533
+ if (isServer) {
1534
+ const apiUrl =
1535
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1536
+ EGDESK_CONFIG.apiUrl;
1537
+ response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
1538
+ method: 'POST',
1539
+ headers: buildServerEgdeskHeaders(),
1540
+ body
1541
+ });
1542
+ } else {
1543
+ response = await apiFetch('/__seo_proxy', {
1544
+ method: 'POST',
1545
+ headers: { 'Content-Type': 'application/json' },
1546
+ body
1547
+ });
1548
+ }
1549
+
1550
+ return parseEgdeskMcpToolResponse(response);
1551
+ }
1552
+
1553
+ /** Run Lighthouse audits on one or more URLs (max 5; ~30–60s per URL) */
1554
+ export async function runLighthouse(
1555
+ urls: string[],
1556
+ options: {
1557
+ proxy?: string;
1558
+ includeAiExplanation?: boolean;
1559
+ } = {}
1560
+ ) {
1561
+ return callSeoTool('seo_run_lighthouse', { urls, ...options });
1562
+ }
1563
+
1564
+ /** List saved SEO Lighthouse report summaries */
1565
+ export async function listSeoReports(options: { url?: string; limit?: number } = {}) {
1566
+ return callSeoTool('seo_list_reports', options);
1567
+ }
1568
+
1569
+ /** Get a saved SEO report by ID */
1570
+ export async function getSeoReport(id: string) {
1571
+ return callSeoTool('seo_get_report', { id });
1572
+ }
1573
+
1574
+ /** Get Lighthouse issues grouped by category for a saved report */
1575
+ export async function getSeoIssuesSummary(reportId: string) {
1576
+ return callSeoTool('seo_get_issues_summary', { reportId });
1577
+ }
1578
+
1579
+ // ==========================================
1580
+ // SSL (MCP)
1581
+ // ==========================================
1582
+
1583
+ /**
1584
+ * Call EGDesk SSL MCP tool (TLS/security analysis and certificate management).
1585
+ *
1586
+ * - Server: \`POST {apiUrl}/ssl/tools/call\`
1587
+ * - Client: \`POST /__ssl_proxy\` (see proxy.ts / middleware)
1588
+ */
1589
+ export async function callSslTool(
1590
+ toolName: string,
1591
+ args: Record<string, any> = {}
1592
+ ): Promise<any> {
1593
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1594
+
1595
+ const isServer = typeof window === 'undefined';
1596
+
1597
+ let response: Response;
1598
+ if (isServer) {
1599
+ const apiUrl =
1600
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1601
+ EGDESK_CONFIG.apiUrl;
1602
+ response = await fetch(\`\${apiUrl}/ssl/tools/call\`, {
1603
+ method: 'POST',
1604
+ headers: buildServerEgdeskHeaders(),
1605
+ body
1606
+ });
1607
+ } else {
1608
+ response = await apiFetch('/__ssl_proxy', {
1609
+ method: 'POST',
1610
+ headers: { 'Content-Type': 'application/json' },
1611
+ body
1612
+ });
1613
+ }
1614
+
1615
+ return parseEgdeskMcpToolResponse(response);
1616
+ }
1617
+
1618
+ /** Full SSL/security audit: cert, headers, and letter grade (A+ to F) */
1619
+ export async function analyzeSslSite(url: string, save: boolean = true) {
1620
+ return callSslTool('ssl_analyze_site', { url, save });
1621
+ }
1622
+
1623
+ /** Inspect TLS certificate for a URL (expiry, issuer, SANs) */
1624
+ export async function checkSslCertificate(url: string) {
1625
+ return callSslTool('ssl_check_certificate', { url });
1626
+ }
1627
+
1628
+ /** Check security headers (HSTS, CSP, X-Frame-Options, etc.) */
1629
+ export async function checkSecurityHeaders(url: string) {
1630
+ return callSslTool('ssl_check_security_headers', { url });
1631
+ }
1632
+
1633
+ /** List saved SSL analysis history entries */
1634
+ export async function listSslAnalyses(options: { websiteUrl?: string; limit?: number } = {}) {
1635
+ return callSslTool('ssl_list_analyses', options);
1636
+ }
1637
+
1638
+ /** Get a saved SSL analysis by ID */
1639
+ export async function getSslAnalysis(id: string) {
1640
+ return callSslTool('ssl_get_analysis', { id });
1641
+ }
1642
+
1643
+ /** List stored SSL certificates (metadata only, no private keys) */
1644
+ export async function listSslCertificates() {
1645
+ return callSslTool('ssl_list_certificates', {});
1646
+ }
1647
+
1648
+ /** Get stored certificate metadata by ID */
1649
+ export async function getSslCertificate(id: string) {
1650
+ return callSslTool('ssl_get_certificate', { id });
1651
+ }
1652
+
1653
+ /** Generate a self-signed certificate for local development */
1654
+ export async function generateSelfSignedCertificate(domain: string) {
1655
+ return callSslTool('ssl_generate_self_signed', { domain });
1656
+ }
1657
+
1658
+ /** Generate a mkcert-trusted local development certificate (macOS) */
1659
+ export async function generateTrustedLocalCertificate(domain: string = 'egdesk.local') {
1660
+ return callSslTool('ssl_generate_trusted_local', { domain });
1661
+ }
1662
+
1663
+ /** Request a Let's Encrypt certificate via ACME HTTP-01 */
1664
+ export async function generateLetsEncryptCertificate(domain: string, email?: string) {
1665
+ return callSslTool('ssl_generate_lets_encrypt', { domain, email });
1666
+ }
1667
+
1668
+ /** Set the active certificate used by EGDesk dev servers */
1669
+ export async function setActiveSslCertificate(certificateId: string | null) {
1670
+ return callSslTool('ssl_set_active_certificate', { certificateId });
1671
+ }
1672
+
1673
+ /** Delete a stored certificate by ID */
1674
+ export async function deleteSslCertificate(id: string) {
1675
+ return callSslTool('ssl_delete_certificate', { id });
1676
+ }
1677
+
1678
+ // ==========================================
1679
+ // Local Agent AI (MCP)
1680
+ // ==========================================
1681
+
1682
+ /**
1683
+ * Call EGDesk Local Agent MCP tool (Ollama + Gemma 4 QAT offline inference).
1684
+ *
1685
+ * Pairs with filesystem MCP (discover/read files) and file-conversion MCP (format changes).
1686
+ *
1687
+ * - Server: \`POST {apiUrl}/local-agent/tools/call\`
1688
+ * - Client: \`POST /__local_agent_proxy\` (see proxy.ts / middleware)
1689
+ */
1690
+ export async function callLocalAgentTool(
1691
+ toolName: string,
1692
+ args: Record<string, any> = {}
1693
+ ): Promise<any> {
1694
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1695
+
1696
+ const isServer = typeof window === 'undefined';
1697
+
1698
+ let response: Response;
1699
+ if (isServer) {
1700
+ const apiUrl =
1701
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1702
+ EGDESK_CONFIG.apiUrl;
1703
+ response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
1704
+ method: 'POST',
1705
+ headers: buildServerEgdeskHeaders(),
1706
+ body
1707
+ });
1708
+ } else {
1709
+ response = await apiFetch('/__local_agent_proxy', {
1710
+ method: 'POST',
1711
+ headers: { 'Content-Type': 'application/json' },
1712
+ body
1713
+ });
1714
+ }
1715
+
1716
+ return parseEgdeskMcpToolResponse(response);
1717
+ }
1718
+
1719
+ /** Check Ollama status, default model install state, and attachment capabilities */
1720
+ export async function getLocalAgentStatus() {
1721
+ return callLocalAgentTool('local_agent_status', {});
1722
+ }
1723
+
1724
+ /**
1725
+ * Pull the default local agent model (Gemma 4 E4B QAT).
1726
+ * Optional \`model\` overrides the Ollama tag.
1727
+ */
1728
+ export async function pullLocalAgentModel(model?: string) {
1729
+ return callLocalAgentTool('local_agent_pull', model ? { model } : {});
1730
+ }
1731
+
1732
+ export type LocalAgentChatMessage = {
1733
+ role: 'system' | 'user' | 'assistant';
1734
+ content: string;
1735
+ };
1736
+
1737
+ export type LocalAgentCallOptions = {
1738
+ messages?: LocalAgentChatMessage[];
1739
+ /** Base64 strings (raw or data URLs) */
1740
+ images?: string[];
1741
+ /** Absolute paths — images, text files, .pdf, .docx (same rules as filesystem MCP) */
1742
+ filePaths?: string[];
1743
+ systemPrompt?: string;
1744
+ model?: string;
1745
+ };
1746
+
1747
+ /**
1748
+ * Run offline chat with the local agent.
1749
+ * Use filesystem MCP (fs_search_files, fs_read_image) to discover files first when needed.
1750
+ */
1751
+ export async function callLocalAgent(prompt: string, options: LocalAgentCallOptions = {}) {
1752
+ return callLocalAgentTool('local_agent_call', { prompt, ...options });
1753
+ }
1754
+
1755
+ // ==========================================
1756
+ // PageIndex (MCP) — PDF RAG
1757
+ // ==========================================
1758
+
1759
+ /**
1760
+ * Call EGDesk PageIndex MCP tool (vectorless PDF indexing and retrieval).
1761
+ *
1762
+ * PDF only. Use filesystem MCP to find files; file-conversion MCP to produce PDFs from other formats.
1763
+ *
1764
+ * - Server: \`POST {apiUrl}/pageindex/tools/call\`
1765
+ * - Client: \`POST /__pageindex_proxy\` (see proxy.ts / middleware)
1766
+ */
1767
+ export async function callPageIndexTool(
1768
+ toolName: string,
1769
+ args: Record<string, any> = {}
1770
+ ): Promise<any> {
1771
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1772
+
1773
+ const isServer = typeof window === 'undefined';
1774
+
1775
+ let response: Response;
1776
+ if (isServer) {
1777
+ const apiUrl =
1778
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1779
+ EGDESK_CONFIG.apiUrl;
1780
+ response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
1781
+ method: 'POST',
1782
+ headers: buildServerEgdeskHeaders(),
1783
+ body
1784
+ });
1785
+ } else {
1786
+ response = await apiFetch('/__pageindex_proxy', {
1787
+ method: 'POST',
1788
+ headers: { 'Content-Type': 'application/json' },
1789
+ body
1790
+ });
1791
+ }
1792
+
1793
+ return parseEgdeskMcpToolResponse(response);
1794
+ }
1795
+
1796
+ /** Index a PDF and build a hierarchical PageIndex tree (30–60s; requires Gemini API key) */
1797
+ export async function indexPageIndexPdf(filePath: string) {
1798
+ return callPageIndexTool('pageindex_index_document', { file_path: filePath });
1799
+ }
1800
+
1801
+ /** List indexed PDF documents */
1802
+ export async function listPageIndexDocuments() {
1803
+ return callPageIndexTool('pageindex_list_documents', {});
1804
+ }
1805
+
1806
+ /** Get metadata for an indexed document */
1807
+ export async function getPageIndexDocument(docId: string) {
1808
+ return callPageIndexTool('pageindex_get_document', { doc_id: docId });
1809
+ }
1810
+
1811
+ /** Get hierarchical structure (titles, page ranges, summaries — no full text) */
1812
+ export async function getPageIndexStructure(docId: string) {
1813
+ return callPageIndexTool('pageindex_get_structure', { doc_id: docId });
1814
+ }
1815
+
1816
+ /** Get raw text for specific pages (e.g. pages: "5", "3,8", "5-7") */
1817
+ export async function getPageIndexPages(docId: string, pages: string) {
1818
+ return callPageIndexTool('pageindex_get_pages', { doc_id: docId, pages });
1819
+ }
1820
+
1821
+ /** Delete an indexed document */
1822
+ export async function deletePageIndexDocument(docId: string) {
1823
+ return callPageIndexTool('pageindex_delete_document', { doc_id: docId });
1824
+ }
1231
1825
  `;
1232
1826
 
1233
1827
  fs.writeFileSync(helperPath, helperContent.replace(/\r?\n/g, os.EOL), 'utf-8');