@egdesk/next-api-plugin 1.5.84 → 1.5.100

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.
@@ -211,6 +211,26 @@ function buildServerEgdeskHeaders(): Record<string, string> {
211
211
  return headers;
212
212
  }
213
213
 
214
+ /**
215
+ * Server-side MCP root for API routes / RSC.
216
+ * Prefer EGDESK_MCP_INTERNAL_URL (localhost) so hosted Next never re-enters the
217
+ * public tunnel for MCP calls (avoids double-hop upload 504s).
218
+ * Browser code must not use this — use /__*_proxy + apiFetch instead.
219
+ */
220
+ function resolveServerEgdeskApiUrl(): string {
221
+ if (typeof process !== 'undefined') {
222
+ const internal = process.env?.EGDESK_MCP_INTERNAL_URL;
223
+ if (internal && String(internal).trim()) {
224
+ return String(internal).replace(/\\/$/, '');
225
+ }
226
+ const pub = process.env?.NEXT_PUBLIC_EGDESK_API_URL;
227
+ if (pub && String(pub).trim()) {
228
+ return String(pub).replace(/\\/$/, '');
229
+ }
230
+ }
231
+ return String(EGDESK_CONFIG.apiUrl || '').replace(/\\/$/, '');
232
+ }
233
+
214
234
  const VISITOR_SESSION_KEY = 'egdesk_visitor_session';
215
235
 
216
236
  export type WorkspaceVisitorCallOptions = {
@@ -299,9 +319,7 @@ async function callWorkspaceMcpTool(
299
319
  const visitorHeaders = buildWorkspaceVisitorHeaders(options);
300
320
  let response: Response;
301
321
  if (isServer) {
302
- const apiUrl =
303
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
304
- EGDESK_CONFIG.apiUrl;
322
+ const apiUrl = resolveServerEgdeskApiUrl();
305
323
  response = await fetch(\`\${apiUrl}\${path}\`, {
306
324
  method: 'POST',
307
325
  headers: { ...buildServerEgdeskHeaders(), ...visitorHeaders },
@@ -432,9 +450,7 @@ export async function callEgdeskHttp(
432
450
  const isServer = typeof window === 'undefined';
433
451
  let response: Response;
434
452
  if (isServer) {
435
- const apiUrl =
436
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
437
- EGDESK_CONFIG.apiUrl;
453
+ const apiUrl = resolveServerEgdeskApiUrl();
438
454
  const base = apiUrl.endsWith('/') ? apiUrl : \`\${apiUrl}/\`;
439
455
  const url = new URL(pathname.startsWith('/') ? pathname.slice(1) : pathname, base);
440
456
  for (const [key, value] of Object.entries(query)) {
@@ -464,9 +480,8 @@ export async function callEgdeskHttp(
464
480
  /**
465
481
  * Call EGDesk user-data MCP tool
466
482
  *
467
- * - Server (API routes): Calls Egdesk API directly using EGDESK_CONFIG.apiUrl and
468
- * EGDESK_CONFIG.apiKey (from env NEXT_PUBLIC_EGDESK_API_URL / NEXT_PUBLIC_EGDESK_API_KEY)
469
- * so relative URLs and tunnel base path are not an issue.
483
+ * - Server (API routes): Calls Egdesk via resolveServerEgdeskApiUrl()
484
+ * (EGDESK_MCP_INTERNAL_URL localhost first, then NEXT_PUBLIC_EGDESK_API_URL) + API key.
470
485
  * - Client (browser): Uses /__user_data_proxy so CORS and tunnel base path still work.
471
486
  */
472
487
  export async function callUserDataTool(
@@ -480,9 +495,7 @@ export async function callUserDataTool(
480
495
  let response: Response;
481
496
  if (isServer) {
482
497
  // API routes: call Egdesk directly (relative URL is invalid in Node)
483
- const apiUrl =
484
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
485
- EGDESK_CONFIG.apiUrl;
498
+ const apiUrl = resolveServerEgdeskApiUrl();
486
499
  response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
487
500
  method: 'POST',
488
501
  headers: buildServerEgdeskHeaders(),
@@ -748,12 +761,251 @@ export async function renameTable(
748
761
  // FILE STORAGE HELPERS
749
762
  // ==========================================
750
763
 
764
+ /** Above this decoded size, uploadFile switches to chunked tunnel-safe uploads. */
765
+ const UPLOAD_CHUNKED_THRESHOLD_BYTES = 4 * 1024 * 1024;
766
+
767
+ function estimateBase64DecodedBytes(data: string): number {
768
+ const trimmed = String(data || '').replace(/^data:[^;]+;base64,/i, '').replace(/\\s/g, '');
769
+ return Math.floor((trimmed.length * 3) / 4);
770
+ }
771
+
772
+ function base64ToUint8Array(data: string): Uint8Array {
773
+ const trimmed = String(data || '').replace(/^data:[^;]+;base64,/i, '').replace(/\\s/g, '');
774
+ const bin = atob(trimmed);
775
+ const out = new Uint8Array(bin.length);
776
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
777
+ return out;
778
+ }
779
+
780
+ async function sha256Hex(buf: ArrayBuffer): Promise<string> {
781
+ const digest = await crypto.subtle.digest('SHA-256', buf);
782
+ return Array.from(new Uint8Array(digest))
783
+ .map((b) => b.toString(16).padStart(2, '0'))
784
+ .join('');
785
+ }
786
+
787
+ export type UploadFileChunkedOptions = {
788
+ mimeType?: string;
789
+ forceStorageType?: 'blob' | 'filesystem';
790
+ compress?: boolean;
791
+ onProgress?: (p: { sentBytes: number; totalBytes: number; sentChunks: number; totalChunks: number }) => void;
792
+ signal?: AbortSignal;
793
+ parallelism?: number;
794
+ };
795
+
796
+ /**
797
+ * Chunked upload for large files (tunnel-safe). Browser sends raw octet-stream chunks
798
+ * to /api/user/files/uploads/*; MCP assembles on disk and path-ingests.
799
+ */
800
+ export async function uploadFileChunked(
801
+ tableName: string,
802
+ rowId: number,
803
+ columnName: string,
804
+ file: Blob | File,
805
+ options: UploadFileChunkedOptions = {},
806
+ ): Promise<any> {
807
+ if (typeof window === 'undefined') {
808
+ throw new Error('uploadFileChunked() is browser-only. On the server, stream to MCP /user-data/uploads directly.');
809
+ }
810
+ const filename =
811
+ (file as File).name ||
812
+ \`upload-\${Date.now()}.bin\`;
813
+ const mimeType = options.mimeType || file.type || 'application/octet-stream';
814
+ const totalBytes = file.size;
815
+ const lastModified = Number((file as File).lastModified) || 0;
816
+ const resumeKey = \`egdesk_chunked_upload:\${tableName}|\${rowId}|\${columnName}|\${filename}|\${totalBytes}|\${lastModified}\`;
817
+ const readResume = (): string => {
818
+ try {
819
+ return localStorage.getItem(resumeKey) || '';
820
+ } catch {
821
+ return '';
822
+ }
823
+ };
824
+ const writeResume = (id: string) => {
825
+ try {
826
+ localStorage.setItem(resumeKey, id);
827
+ } catch {
828
+ // ignore quota / private mode
829
+ }
830
+ };
831
+ const clearResume = () => {
832
+ try {
833
+ localStorage.removeItem(resumeKey);
834
+ } catch {
835
+ // ignore
836
+ }
837
+ };
838
+
839
+ let uploadId = readResume();
840
+ let chunkSize = 0;
841
+ let totalChunks = 0;
842
+
843
+ if (uploadId) {
844
+ const statusRes = await apiFetch(\`/api/user/files/uploads/\${uploadId}\`, { signal: options.signal });
845
+ const statusJson = await statusRes.json().catch(() => ({}));
846
+ if (
847
+ statusRes.ok &&
848
+ statusJson.success !== false &&
849
+ (statusJson.state === 'receiving' || statusJson.state === 'finalizing') &&
850
+ Number(statusJson.size) === totalBytes
851
+ ) {
852
+ chunkSize = Number(statusJson.chunkSize);
853
+ totalChunks = Number(statusJson.totalChunks || Math.ceil(totalBytes / chunkSize));
854
+ } else if (statusRes.ok && statusJson.state === 'done' && statusJson.file) {
855
+ clearResume();
856
+ return {
857
+ success: true,
858
+ uploadId,
859
+ file: statusJson.file,
860
+ state: 'done',
861
+ sha256: statusJson.sha256,
862
+ resumed: true,
863
+ };
864
+ } else {
865
+ clearResume();
866
+ uploadId = '';
867
+ }
868
+ }
869
+
870
+ if (!uploadId) {
871
+ const initRes = await apiFetch('/api/user/files/uploads', {
872
+ method: 'POST',
873
+ headers: { 'Content-Type': 'application/json' },
874
+ body: JSON.stringify({
875
+ filename,
876
+ size: totalBytes,
877
+ mimeType,
878
+ tableName,
879
+ rowId,
880
+ columnName,
881
+ forceStorageType: options.forceStorageType,
882
+ compress: options.compress,
883
+ }),
884
+ signal: options.signal,
885
+ });
886
+ const initJson = await initRes.json();
887
+ if (!initRes.ok || initJson.success === false) {
888
+ throw new Error(initJson.error || initJson.message || \`Init upload failed (HTTP \${initRes.status})\`);
889
+ }
890
+ uploadId = String(initJson.uploadId);
891
+ chunkSize = Number(initJson.chunkSize);
892
+ totalChunks = Number(initJson.totalChunks || Math.ceil(totalBytes / chunkSize));
893
+ writeResume(uploadId);
894
+ }
895
+
896
+ const parallelism = Math.max(1, Math.min(options.parallelism ?? 3, 3));
897
+
898
+ const statusRes = await apiFetch(\`/api/user/files/uploads/\${uploadId}\`, { signal: options.signal });
899
+ const statusJson = await statusRes.json().catch(() => ({}));
900
+ const already = new Set<number>(Array.isArray(statusJson.received) ? statusJson.received : []);
901
+
902
+ let sentBytes = Math.min(totalBytes, already.size * chunkSize);
903
+ let sentChunks = already.size;
904
+ options.onProgress?.({ sentBytes, totalBytes, sentChunks, totalChunks });
905
+
906
+ const pending: number[] = [];
907
+ for (let i = 0; i < totalChunks; i++) {
908
+ if (!already.has(i)) pending.push(i);
909
+ }
910
+
911
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
912
+ const backoffs = [500, 1500, 4000];
913
+
914
+ async function putOne(index: number): Promise<void> {
915
+ const start = index * chunkSize;
916
+ const end = Math.min(start + chunkSize, totalBytes);
917
+ const slice = file.slice(start, end);
918
+ const buf = await slice.arrayBuffer();
919
+ const sha = await sha256Hex(buf);
920
+ let lastErr: Error | null = null;
921
+ for (let attempt = 0; attempt < 3; attempt++) {
922
+ if (options.signal?.aborted) throw new Error('Upload aborted');
923
+ try {
924
+ const res = await apiFetch(\`/api/user/files/uploads/\${uploadId}/chunks/\${index}\`, {
925
+ method: 'PUT',
926
+ headers: {
927
+ 'Content-Type': 'application/octet-stream',
928
+ 'x-chunk-sha256': sha,
929
+ },
930
+ body: buf,
931
+ signal: options.signal,
932
+ });
933
+ const json = await res.json().catch(() => ({}));
934
+ if (res.status === 401 && attempt < 2) {
935
+ await sleep(backoffs[attempt]);
936
+ continue;
937
+ }
938
+ if (!res.ok || json.success === false) {
939
+ throw new Error(json.error || json.message || \`Chunk \${index} failed (HTTP \${res.status})\`);
940
+ }
941
+ sentChunks += 1;
942
+ sentBytes = Math.min(totalBytes, sentBytes + (end - start));
943
+ options.onProgress?.({ sentBytes, totalBytes, sentChunks, totalChunks });
944
+ return;
945
+ } catch (e: any) {
946
+ lastErr = e instanceof Error ? e : new Error(String(e));
947
+ if (attempt < 2) await sleep(backoffs[attempt]);
948
+ }
949
+ }
950
+ throw lastErr || new Error(\`Chunk \${index} failed\`);
951
+ }
952
+
953
+ let cursor = 0;
954
+ async function worker() {
955
+ while (cursor < pending.length) {
956
+ const idx = pending[cursor++];
957
+ await putOne(idx);
958
+ }
959
+ }
960
+ await Promise.all(Array.from({ length: Math.min(parallelism, pending.length || 1) }, () => worker()));
961
+
962
+ const completeRes = await apiFetch(\`/api/user/files/uploads/\${uploadId}/complete\`, {
963
+ method: 'POST',
964
+ headers: { 'Content-Type': 'application/json' },
965
+ body: '{}',
966
+ signal: options.signal,
967
+ });
968
+ let completeJson = await completeRes.json();
969
+ if (!completeRes.ok && completeRes.status !== 202) {
970
+ throw new Error(completeJson.error || completeJson.message || \`Complete failed (HTTP \${completeRes.status})\`);
971
+ }
972
+
973
+ // Poll when finalizing in background
974
+ if (completeJson.state === 'finalizing' || completeRes.status === 202) {
975
+ for (let i = 0; i < 600; i++) {
976
+ if (options.signal?.aborted) throw new Error('Upload aborted');
977
+ await sleep(500);
978
+ const st = await apiFetch(\`/api/user/files/uploads/\${uploadId}\`, { signal: options.signal });
979
+ const sj = await st.json();
980
+ if (sj.state === 'done') {
981
+ completeJson = sj;
982
+ break;
983
+ }
984
+ if (sj.state === 'failed') {
985
+ throw new Error(sj.error || 'Upload finalization failed');
986
+ }
987
+ }
988
+ if (completeJson.state !== 'done') {
989
+ throw new Error('Timed out waiting for upload finalization');
990
+ }
991
+ }
992
+
993
+ clearResume();
994
+ return {
995
+ success: true,
996
+ uploadId,
997
+ file: completeJson.file,
998
+ state: completeJson.state || 'done',
999
+ sha256: completeJson.sha256,
1000
+ };
1001
+ }
1002
+
751
1003
  /**
752
1004
  * Upload a file attachment for a table row.
753
1005
  * Files are NOT table columns — they attach via a virtual columnName (e.g. "file").
754
1006
  * Workflow: insertRows(...) → uploadFile(tableName, rowId, 'file', filename, base64).
755
- * Data must be base64 (raw or data URL). Files <10KB store as uncompressed blobs,
756
- * 10-100KB as gzip blobs, >100KB on disk via BucketManager.
1007
+ * Data must be base64 (raw or data URL). Files >4 MiB automatically use chunked upload
1008
+ * in the browser (tunnel-safe). Small files still use a single Base64 MCP call.
757
1009
  */
758
1010
  export async function uploadFile(
759
1011
  tableName: string,
@@ -767,6 +1019,13 @@ export async function uploadFile(
767
1019
  compress?: boolean;
768
1020
  } = {}
769
1021
  ) {
1022
+ const decodedBytes = estimateBase64DecodedBytes(data);
1023
+ if (typeof window !== 'undefined' && decodedBytes > UPLOAD_CHUNKED_THRESHOLD_BYTES) {
1024
+ const bytes = base64ToUint8Array(data);
1025
+ const blob = new Blob([bytes], { type: options.mimeType || 'application/octet-stream' });
1026
+ const file = new File([blob], filename, { type: options.mimeType || blob.type });
1027
+ return uploadFileChunked(tableName, rowId, columnName, file, options);
1028
+ }
770
1029
  return callUserDataTool('user_data_upload_file', {
771
1030
  tableName,
772
1031
  rowId,
@@ -1113,9 +1372,7 @@ export async function callKakaoTool(
1113
1372
 
1114
1373
  let response: Response;
1115
1374
  if (isServer) {
1116
- const apiUrl =
1117
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1118
- EGDESK_CONFIG.apiUrl;
1375
+ const apiUrl = resolveServerEgdeskApiUrl();
1119
1376
  response = await fetch(\`\${apiUrl}/kakao/tools/call\`, {
1120
1377
  method: 'POST',
1121
1378
  headers: buildServerEgdeskHeaders(),
@@ -1301,9 +1558,7 @@ export async function callFinanceHubTool(
1301
1558
 
1302
1559
  let response: Response;
1303
1560
  if (isServer) {
1304
- const apiUrl =
1305
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1306
- EGDESK_CONFIG.apiUrl;
1561
+ const apiUrl = resolveServerEgdeskApiUrl();
1307
1562
  response = await fetch(\`\${apiUrl}/financehub/tools/call\`, {
1308
1563
  method: 'POST',
1309
1564
  headers: buildServerEgdeskHeaders(),
@@ -1639,9 +1894,7 @@ export async function callBusinessIdentityTool(
1639
1894
 
1640
1895
  let response: Response;
1641
1896
  if (isServer) {
1642
- const apiUrl =
1643
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1644
- EGDESK_CONFIG.apiUrl;
1897
+ const apiUrl = resolveServerEgdeskApiUrl();
1645
1898
  response = await fetch(\`\${apiUrl}/business-identity/tools/call\`, {
1646
1899
  method: 'POST',
1647
1900
  headers: buildServerEgdeskHeaders(),
@@ -1725,9 +1978,7 @@ export async function callCompanyResearchTool(
1725
1978
 
1726
1979
  let response: Response;
1727
1980
  if (isServer) {
1728
- const apiUrl =
1729
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1730
- EGDESK_CONFIG.apiUrl;
1981
+ const apiUrl = resolveServerEgdeskApiUrl();
1731
1982
  response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
1732
1983
  method: 'POST',
1733
1984
  headers: buildServerEgdeskHeaders(),
@@ -1873,9 +2124,7 @@ export async function callBrowserRecordingTool(
1873
2124
 
1874
2125
  let response: Response;
1875
2126
  if (isServer) {
1876
- const apiUrl =
1877
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1878
- EGDESK_CONFIG.apiUrl;
2127
+ const apiUrl = resolveServerEgdeskApiUrl();
1879
2128
  response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
1880
2129
  method: 'POST',
1881
2130
  headers: buildServerEgdeskHeaders(),
@@ -2284,9 +2533,7 @@ export async function callAICenterTool(
2284
2533
 
2285
2534
  let response: Response;
2286
2535
  if (isServer) {
2287
- const apiUrl =
2288
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2289
- EGDESK_CONFIG.apiUrl;
2536
+ const apiUrl = resolveServerEgdeskApiUrl();
2290
2537
  response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
2291
2538
  method: 'POST',
2292
2539
  headers: buildServerEgdeskHeaders(),
@@ -2560,9 +2807,7 @@ export async function callKoreanLawTool(
2560
2807
 
2561
2808
  let response: Response;
2562
2809
  if (isServer) {
2563
- const apiUrl =
2564
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2565
- EGDESK_CONFIG.apiUrl;
2810
+ const apiUrl = resolveServerEgdeskApiUrl();
2566
2811
  response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
2567
2812
  method: 'POST',
2568
2813
  headers: buildServerEgdeskHeaders(),
@@ -2786,9 +3031,7 @@ export async function callSeoTool(
2786
3031
 
2787
3032
  let response: Response;
2788
3033
  if (isServer) {
2789
- const apiUrl =
2790
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2791
- EGDESK_CONFIG.apiUrl;
3034
+ const apiUrl = resolveServerEgdeskApiUrl();
2792
3035
  response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
2793
3036
  method: 'POST',
2794
3037
  headers: buildServerEgdeskHeaders(),
@@ -2851,9 +3094,7 @@ export async function callHostingCodingTool(
2851
3094
 
2852
3095
  let response: Response;
2853
3096
  if (isServer) {
2854
- const apiUrl =
2855
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2856
- EGDESK_CONFIG.apiUrl;
3097
+ const apiUrl = resolveServerEgdeskApiUrl();
2857
3098
  response = await fetch(\`\${apiUrl}/hosting-coding/tools/call\`, {
2858
3099
  method: 'POST',
2859
3100
  headers: buildServerEgdeskHeaders(),
@@ -2992,9 +3233,7 @@ export async function callLocalAgentTool(
2992
3233
 
2993
3234
  let response: Response;
2994
3235
  if (isServer) {
2995
- const apiUrl =
2996
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2997
- EGDESK_CONFIG.apiUrl;
3236
+ const apiUrl = resolveServerEgdeskApiUrl();
2998
3237
  response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
2999
3238
  method: 'POST',
3000
3239
  headers: buildServerEgdeskHeaders(),
@@ -3069,9 +3308,7 @@ export async function callAiCallerTool(
3069
3308
 
3070
3309
  let response: Response;
3071
3310
  if (isServer) {
3072
- const apiUrl =
3073
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3074
- EGDESK_CONFIG.apiUrl;
3311
+ const apiUrl = resolveServerEgdeskApiUrl();
3075
3312
  response = await fetch(\`\${apiUrl}/ai-caller/tools/call\`, {
3076
3313
  method: 'POST',
3077
3314
  headers: buildServerEgdeskHeaders(),
@@ -3390,9 +3627,7 @@ export async function callPageIndexTool(
3390
3627
 
3391
3628
  let response: Response;
3392
3629
  if (isServer) {
3393
- const apiUrl =
3394
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3395
- EGDESK_CONFIG.apiUrl;
3630
+ const apiUrl = resolveServerEgdeskApiUrl();
3396
3631
  response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
3397
3632
  method: 'POST',
3398
3633
  headers: buildServerEgdeskHeaders(),
@@ -4173,9 +4408,7 @@ export async function callKnowledgeWikiTool(
4173
4408
 
4174
4409
  let response: Response;
4175
4410
  if (isServer) {
4176
- const apiUrl =
4177
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4178
- EGDESK_CONFIG.apiUrl;
4411
+ const apiUrl = resolveServerEgdeskApiUrl();
4179
4412
  response = await fetch(\`\${apiUrl}/knowledge-wiki/tools/call\`, {
4180
4413
  method: 'POST',
4181
4414
  headers: buildServerEgdeskHeaders(),
@@ -4285,9 +4518,7 @@ export async function callEgdeskConfigTool(
4285
4518
 
4286
4519
  let response: Response;
4287
4520
  if (isServer) {
4288
- const apiUrl =
4289
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4290
- EGDESK_CONFIG.apiUrl;
4521
+ const apiUrl = resolveServerEgdeskApiUrl();
4291
4522
  response = await fetch(\`\${apiUrl}/egdesk-config/tools/call\`, {
4292
4523
  method: 'POST',
4293
4524
  headers: buildServerEgdeskHeaders(),
@@ -4403,9 +4634,7 @@ export async function callPhoneTool(
4403
4634
 
4404
4635
  let response: Response;
4405
4636
  if (isServer) {
4406
- const apiUrl =
4407
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4408
- EGDESK_CONFIG.apiUrl;
4637
+ const apiUrl = resolveServerEgdeskApiUrl();
4409
4638
  response = await fetch(\`\${apiUrl}/phone/tools/call\`, {
4410
4639
  method: 'POST',
4411
4640
  headers: buildServerEgdeskHeaders(),
@@ -4666,9 +4895,7 @@ export async function callInstagramTool(
4666
4895
 
4667
4896
  let response: Response;
4668
4897
  if (isServer) {
4669
- const apiUrl =
4670
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4671
- EGDESK_CONFIG.apiUrl;
4898
+ const apiUrl = resolveServerEgdeskApiUrl();
4672
4899
  response = await fetch(\`\${apiUrl}/instagram/tools/call\`, {
4673
4900
  method: 'POST',
4674
4901
  headers: buildServerEgdeskHeaders(),
@@ -5001,9 +5228,7 @@ export async function callBlogTool(
5001
5228
 
5002
5229
  let response: Response;
5003
5230
  if (isServer) {
5004
- const apiUrl =
5005
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
5006
- EGDESK_CONFIG.apiUrl;
5231
+ const apiUrl = resolveServerEgdeskApiUrl();
5007
5232
  response = await fetch(\`\${apiUrl}/blog/tools/call\`, {
5008
5233
  method: 'POST',
5009
5234
  headers: buildServerEgdeskHeaders(),
@@ -5285,9 +5510,7 @@ export async function callYouTubeTool(
5285
5510
 
5286
5511
  let response: Response;
5287
5512
  if (isServer) {
5288
- const apiUrl =
5289
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
5290
- EGDESK_CONFIG.apiUrl;
5513
+ const apiUrl = resolveServerEgdeskApiUrl();
5291
5514
  response = await fetch(\`\${apiUrl}/youtube/tools/call\`, {
5292
5515
  method: 'POST',
5293
5516
  headers: buildServerEgdeskHeaders(),
@@ -114,6 +114,13 @@ function workspaceUpstreamHeaders(request: NextRequest): Record<string, string>
114
114
  return headers;
115
115
  }
116
116
 
117
+ /** Prefer loopback MCP so middleware hops never re-enter the public tunnel. */
118
+ function resolveEgdeskMcpApiUrl(): string {
119
+ const internal = process.env.EGDESK_MCP_INTERNAL_URL;
120
+ if (internal && internal.trim()) return internal.replace(/\\/$/, '');
121
+ return (process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080').replace(/\\/$/, '');
122
+ }
123
+
117
124
  export async function middleware(request: NextRequest) {
118
125
  const { pathname } = request.nextUrl;
119
126
 
@@ -124,7 +131,7 @@ export async function middleware(request: NextRequest) {
124
131
 
125
132
  // Read API key and URL from environment
126
133
  const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
127
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
134
+ const apiUrl = resolveEgdeskMcpApiUrl();
128
135
 
129
136
  const headers: HeadersInit = {
130
137
  'Content-Type': 'application/json',
@@ -157,7 +164,7 @@ export async function middleware(request: NextRequest) {
157
164
  const body = await request.text();
158
165
 
159
166
  const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
160
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
167
+ const apiUrl = resolveEgdeskMcpApiUrl();
161
168
 
162
169
  const headers: HeadersInit = {
163
170
  'Content-Type': 'application/json',
@@ -189,7 +196,7 @@ export async function middleware(request: NextRequest) {
189
196
  const body = await request.text();
190
197
 
191
198
  const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
192
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
199
+ const apiUrl = resolveEgdeskMcpApiUrl();
193
200
 
194
201
  const headers: HeadersInit = {
195
202
  'Content-Type': 'application/json',
@@ -221,7 +228,7 @@ export async function middleware(request: NextRequest) {
221
228
  const body = await request.text();
222
229
 
223
230
  const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
224
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
231
+ const apiUrl = resolveEgdeskMcpApiUrl();
225
232
 
226
233
  const headers: HeadersInit = {
227
234
  'Content-Type': 'application/json',
@@ -253,7 +260,7 @@ export async function middleware(request: NextRequest) {
253
260
  const body = await request.text();
254
261
 
255
262
  const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
256
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
263
+ const apiUrl = resolveEgdeskMcpApiUrl();
257
264
 
258
265
  const headers: HeadersInit = {
259
266
  'Content-Type': 'application/json',
@@ -283,7 +290,7 @@ export async function middleware(request: NextRequest) {
283
290
  if (pathname.includes('__drive_proxy')) {
284
291
  try {
285
292
  const body = await request.text();
286
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
293
+ const apiUrl = resolveEgdeskMcpApiUrl();
287
294
 
288
295
  const response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
289
296
  method: 'POST',
@@ -303,7 +310,7 @@ export async function middleware(request: NextRequest) {
303
310
  if (pathname.includes('__docs_proxy')) {
304
311
  try {
305
312
  const body = await request.text();
306
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
313
+ const apiUrl = resolveEgdeskMcpApiUrl();
307
314
 
308
315
  const response = await fetch(\`\${apiUrl}/docs/tools/call\`, {
309
316
  method: 'POST',
@@ -323,7 +330,7 @@ export async function middleware(request: NextRequest) {
323
330
  if (pathname.includes('__slides_proxy')) {
324
331
  try {
325
332
  const body = await request.text();
326
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
333
+ const apiUrl = resolveEgdeskMcpApiUrl();
327
334
 
328
335
  const response = await fetch(\`\${apiUrl}/slides/tools/call\`, {
329
336
  method: 'POST',
@@ -343,7 +350,7 @@ export async function middleware(request: NextRequest) {
343
350
  if (pathname.includes('__sheets_proxy')) {
344
351
  try {
345
352
  const body = await request.text();
346
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
353
+ const apiUrl = resolveEgdeskMcpApiUrl();
347
354
 
348
355
  const response = await fetch(\`\${apiUrl}/sheets/tools/call\`, {
349
356
  method: 'POST',
@@ -370,7 +377,7 @@ export async function middleware(request: NextRequest) {
370
377
  }
371
378
  const method = payload.method === 'POST' ? 'POST' : 'GET';
372
379
  const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
373
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
380
+ const apiUrl = resolveEgdeskMcpApiUrl();
374
381
  const projectId = process.env.NEXT_PUBLIC_EGDESK_PROJECT_ID;
375
382
  const egdeskEnv = process.env.NEXT_PUBLIC_EGDESK_ENV;
376
383
  const headers: HeadersInit = { 'Content-Type': 'application/json' };
@@ -401,7 +408,7 @@ export async function middleware(request: NextRequest) {
401
408
  if (pathname.includes('__gmail_proxy')) {
402
409
  try {
403
410
  const body = await request.text();
404
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
411
+ const apiUrl = resolveEgdeskMcpApiUrl();
405
412
  const response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
406
413
  method: 'POST',
407
414
  headers: workspaceUpstreamHeaders(request),
@@ -420,7 +427,7 @@ export async function middleware(request: NextRequest) {
420
427
  if (pathname.includes('__apps_script_proxy')) {
421
428
  try {
422
429
  const body = await request.text();
423
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
430
+ const apiUrl = resolveEgdeskMcpApiUrl();
424
431
  const response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
425
432
  method: 'POST',
426
433
  headers: workspaceUpstreamHeaders(request),
@@ -439,7 +446,7 @@ export async function middleware(request: NextRequest) {
439
446
  if (pathname.includes('__visitor_auth_proxy')) {
440
447
  try {
441
448
  const body = await request.text();
442
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
449
+ const apiUrl = resolveEgdeskMcpApiUrl();
443
450
 
444
451
  const response = await fetch(\`\${apiUrl}/visitor-auth/tools/call\`, {
445
452
  method: 'POST',
@@ -459,7 +466,7 @@ export async function middleware(request: NextRequest) {
459
466
  if (pathname.includes('__visitor_google_proxy')) {
460
467
  try {
461
468
  const body = await request.text();
462
- const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
469
+ const apiUrl = resolveEgdeskMcpApiUrl();
463
470
  const headers = visitorUpstreamHeaders(request);
464
471
  const authorization = request.headers.get('authorization');
465
472
  if (authorization) headers['Authorization'] = authorization;