@raiseinfo/smartorder-stdio-mcp 1.0.1 → 1.0.2

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.
@@ -1,10 +1,13 @@
1
1
  import { McpConfigResponse, McpUploadResponse } from '../types/index.js';
2
2
  export declare class HttpClient {
3
- private baseUrl;
4
- private tenantCode;
5
- private mcpToken;
6
- constructor();
3
+ private get baseUrl();
4
+ private get tenantCode();
5
+ private get mcpToken();
6
+ private get authHeaders();
7
7
  getConfig(): Promise<McpConfigResponse>;
8
8
  uploadFile(filePath: string, folder: string, apiUrl?: string): Promise<McpUploadResponse>;
9
+ private uploadWithRetry;
10
+ private doUpload;
9
11
  private request;
12
+ private handleResponse;
10
13
  }
@@ -3,96 +3,106 @@ import path from 'path';
3
3
  import FormData from 'form-data';
4
4
  import http from 'http';
5
5
  import https from 'https';
6
+ const MAX_RETRIES = 2;
6
7
  export class HttpClient {
7
- baseUrl;
8
- tenantCode;
9
- mcpToken;
10
- constructor() {
11
- this.baseUrl = process.env.SMARTORDER_API_BASE || 'https://smart-order.raiseinfo.cn';
12
- this.tenantCode = process.env.TENANT_CODE || '';
13
- this.mcpToken = process.env.MCP_TOKEN || '';
8
+ get baseUrl() {
9
+ return process.env.SMARTORDER_API_BASE || 'https://smart-order.raiseinfo.cn';
10
+ }
11
+ get tenantCode() {
12
+ return process.env.TENANT_CODE || '';
13
+ }
14
+ get mcpToken() {
15
+ return process.env.MCP_TOKEN || '';
16
+ }
17
+ get authHeaders() {
18
+ return {
19
+ 'X-Tenant-Code': this.tenantCode,
20
+ 'X-Mcp-Token': this.mcpToken,
21
+ };
14
22
  }
15
23
  async getConfig() {
16
24
  const url = `${this.baseUrl}/api/mcp/config`;
17
- console.log('[HTTP] GET config from:', url);
18
- console.log('[HTTP] Headers:', {
19
- 'X-Tenant-Code': this.tenantCode ? '***' : 'EMPTY',
20
- 'X-Mcp-Token': this.mcpToken ? '***' : 'EMPTY'
21
- });
22
- const result = await this.request('GET', url);
23
- console.log('[HTTP] GET config response:', JSON.stringify(result, null, 2));
24
- return result;
25
+ console.log('[HTTP] GET', url);
26
+ return this.request('GET', url);
25
27
  }
26
28
  async uploadFile(filePath, folder, apiUrl) {
27
29
  const url = apiUrl || `${this.baseUrl}/api/mcp/upload`;
28
- console.log('[HTTP] POST upload to:', url);
29
- console.log('[HTTP] File:', filePath, 'Folder:', folder);
30
- const form = new FormData();
31
- const fileStream = fs.createReadStream(filePath);
32
- const fileName = path.basename(filePath);
33
- form.append('file', fileStream, { filename: fileName });
34
- form.append('folder', folder);
35
- const result = await this.request('POST', url, form, true);
36
- console.log('[HTTP] Upload response:', JSON.stringify(result, null, 2));
37
- return result;
30
+ return this.uploadWithRetry(filePath, folder, url);
31
+ }
32
+ async uploadWithRetry(filePath, folder, url, attempt = 1) {
33
+ console.log(`[HTTP] Upload attempt ${attempt}/${MAX_RETRIES + 1}:`, filePath);
34
+ try {
35
+ return await this.doUpload(filePath, folder, url);
36
+ }
37
+ catch (error) {
38
+ console.error(`[HTTP] Upload attempt ${attempt} failed:`, error.message);
39
+ if (attempt <= MAX_RETRIES) {
40
+ console.log(`[HTTP] Retrying... (${attempt + 1}/${MAX_RETRIES + 1})`);
41
+ return this.uploadWithRetry(filePath, folder, url, attempt + 1);
42
+ }
43
+ throw error;
44
+ }
45
+ }
46
+ doUpload(filePath, folder, url) {
47
+ return new Promise((resolve, reject) => {
48
+ const form = new FormData();
49
+ form.append('file', fs.createReadStream(filePath), { filename: path.basename(filePath) });
50
+ form.append('folder', folder);
51
+ const urlObj = new URL(url);
52
+ const client = urlObj.protocol === 'https:' ? https : http;
53
+ const req = client.request({
54
+ hostname: urlObj.hostname,
55
+ port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
56
+ path: urlObj.pathname,
57
+ method: 'POST',
58
+ headers: { ...this.authHeaders, ...form.getHeaders() },
59
+ });
60
+ this.handleResponse(req, resolve, reject);
61
+ req.on('error', (err) => reject(new Error(`网络错误:${err.message}`)));
62
+ form.pipe(req);
63
+ });
38
64
  }
39
- request(method, url, body, isFormData = false) {
65
+ request(method, url) {
40
66
  return new Promise((resolve, reject) => {
41
67
  const urlObj = new URL(url);
42
68
  const client = urlObj.protocol === 'https:' ? https : http;
43
- const options = {
69
+ const req = client.request({
44
70
  hostname: urlObj.hostname,
45
71
  port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
46
72
  path: urlObj.pathname,
47
73
  method,
48
- headers: {
49
- 'X-Tenant-Code': this.tenantCode,
50
- 'X-Mcp-Token': this.mcpToken,
51
- ...(isFormData ? body.getHeaders() : { 'Content-Type': 'application/json' }),
52
- },
53
- };
54
- console.log('[HTTP] Request:', method, url);
55
- const req = client.request(options, (res) => {
56
- let data = '';
57
- console.log('[HTTP] Response status:', res.statusCode);
58
- res.on('data', (chunk) => (data += chunk));
59
- res.on('end', () => {
60
- console.log('[HTTP] Raw response:', data);
61
- try {
62
- const json = JSON.parse(data);
63
- if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
64
- resolve(json);
65
- }
66
- else if (res.statusCode === 401 || res.statusCode === 403) {
67
- reject(new Error('认证失败,请检查租户Token配置'));
68
- }
69
- else if (res.statusCode === 404) {
70
- reject(new Error('上传服务路径不存在,请联系管理员'));
71
- }
72
- else {
73
- reject(new Error(`服务返回错误:${res.statusCode}`));
74
- }
74
+ headers: { ...this.authHeaders, 'Content-Type': 'application/json' },
75
+ });
76
+ this.handleResponse(req, resolve, reject);
77
+ req.on('error', (err) => reject(new Error(`网络错误:${err.message}`)));
78
+ req.end();
79
+ });
80
+ }
81
+ handleResponse(req, resolve, reject) {
82
+ req.on('response', (res) => {
83
+ let data = '';
84
+ res.on('data', (chunk) => (data += chunk));
85
+ res.on('end', () => {
86
+ console.log('[HTTP] Response:', res.statusCode, data.substring(0, 200));
87
+ try {
88
+ const json = JSON.parse(data);
89
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
90
+ resolve(json);
75
91
  }
76
- catch (e) {
77
- console.error('[HTTP] Parse error:', e);
78
- console.error('[HTTP] Raw data:', data);
79
- reject(new Error('响应解析失败: ' + data));
92
+ else if (res.statusCode === 401 || res.statusCode === 403) {
93
+ reject(new Error('认证失败,请检查租户Token配置'));
94
+ }
95
+ else if (res.statusCode === 404) {
96
+ reject(new Error('上传服务路径不存在,请联系管理员'));
97
+ }
98
+ else {
99
+ reject(new Error(`服务返回错误:${res.statusCode}`));
80
100
  }
81
- });
82
- });
83
- req.on('error', (err) => {
84
- console.error('[HTTP] Request error:', err);
85
- reject(new Error(`网络错误:${err.message}`));
86
- });
87
- if (body) {
88
- if (isFormData) {
89
- body.pipe(req);
90
101
  }
91
- else {
92
- req.write(JSON.stringify(body));
102
+ catch (e) {
103
+ reject(new Error('响应解析失败: ' + data.substring(0, 100)));
93
104
  }
94
- }
95
- req.end();
105
+ });
96
106
  });
97
107
  }
98
108
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raiseinfo/smartorder-stdio-mcp",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "type": "module",
5
5
  "description": "智单通文件上传 MCP Server (stdio模式)",
6
6
  "bin": {
@@ -5,110 +5,128 @@ import http from 'http';
5
5
  import https from 'https';
6
6
  import { McpConfigResponse, McpUploadResponse } from '../types/index.js';
7
7
 
8
+ const MAX_RETRIES = 2;
9
+
8
10
  export class HttpClient {
9
- private baseUrl: string;
10
- private tenantCode: string;
11
- private mcpToken: string;
12
-
13
- constructor() {
14
- this.baseUrl = process.env.SMARTORDER_API_BASE || 'https://smart-order.raiseinfo.cn';
15
- this.tenantCode = process.env.TENANT_CODE || '';
16
- this.mcpToken = process.env.MCP_TOKEN || '';
11
+ private get baseUrl(): string {
12
+ return process.env.SMARTORDER_API_BASE || 'https://smart-order.raiseinfo.cn';
13
+ }
14
+
15
+ private get tenantCode(): string {
16
+ return process.env.TENANT_CODE || '';
17
+ }
18
+
19
+ private get mcpToken(): string {
20
+ return process.env.MCP_TOKEN || '';
21
+ }
22
+
23
+ private get authHeaders(): Record<string, string> {
24
+ return {
25
+ 'X-Tenant-Code': this.tenantCode,
26
+ 'X-Mcp-Token': this.mcpToken,
27
+ };
17
28
  }
18
29
 
19
30
  async getConfig(): Promise<McpConfigResponse> {
20
31
  const url = `${this.baseUrl}/api/mcp/config`;
21
- console.log('[HTTP] GET config from:', url);
22
- console.log('[HTTP] Headers:', {
23
- 'X-Tenant-Code': this.tenantCode ? '***' : 'EMPTY',
24
- 'X-Mcp-Token': this.mcpToken ? '***' : 'EMPTY'
25
- });
26
- const result = await this.request('GET', url);
27
- console.log('[HTTP] GET config response:', JSON.stringify(result, null, 2));
28
- return result as McpConfigResponse;
32
+ console.log('[HTTP] GET', url);
33
+ return this.request('GET', url) as Promise<McpConfigResponse>;
29
34
  }
30
35
 
31
36
  async uploadFile(filePath: string, folder: string, apiUrl?: string): Promise<McpUploadResponse> {
32
37
  const url = apiUrl || `${this.baseUrl}/api/mcp/upload`;
33
- console.log('[HTTP] POST upload to:', url);
34
- console.log('[HTTP] File:', filePath, 'Folder:', folder);
35
- const form = new FormData();
38
+ return this.uploadWithRetry(filePath, folder, url);
39
+ }
36
40
 
37
- const fileStream = fs.createReadStream(filePath);
38
- const fileName = path.basename(filePath);
41
+ private async uploadWithRetry(
42
+ filePath: string,
43
+ folder: string,
44
+ url: string,
45
+ attempt: number = 1
46
+ ): Promise<McpUploadResponse> {
47
+ console.log(`[HTTP] Upload attempt ${attempt}/${MAX_RETRIES + 1}:`, filePath);
39
48
 
40
- form.append('file', fileStream, { filename: fileName });
41
- form.append('folder', folder);
49
+ try {
50
+ return await this.doUpload(filePath, folder, url);
51
+ } catch (error: any) {
52
+ console.error(`[HTTP] Upload attempt ${attempt} failed:`, error.message);
42
53
 
43
- const result = await this.request('POST', url, form, true);
44
- console.log('[HTTP] Upload response:', JSON.stringify(result, null, 2));
45
- return result as McpUploadResponse;
54
+ if (attempt <= MAX_RETRIES) {
55
+ console.log(`[HTTP] Retrying... (${attempt + 1}/${MAX_RETRIES + 1})`);
56
+ return this.uploadWithRetry(filePath, folder, url, attempt + 1);
57
+ }
58
+ throw error;
59
+ }
46
60
  }
47
61
 
48
- private request(
49
- method: string,
50
- url: string,
51
- body?: any,
52
- isFormData: boolean = false
53
- ): Promise<any> {
62
+ private doUpload(filePath: string, folder: string, url: string): Promise<McpUploadResponse> {
54
63
  return new Promise((resolve, reject) => {
64
+ const form = new FormData();
65
+ form.append('file', fs.createReadStream(filePath), { filename: path.basename(filePath) });
66
+ form.append('folder', folder);
67
+
55
68
  const urlObj = new URL(url);
56
69
  const client = urlObj.protocol === 'https:' ? https : http;
57
70
 
58
- const options: http.RequestOptions = {
71
+ const req = client.request({
59
72
  hostname: urlObj.hostname,
60
73
  port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
61
74
  path: urlObj.pathname,
62
- method,
63
- headers: {
64
- 'X-Tenant-Code': this.tenantCode,
65
- 'X-Mcp-Token': this.mcpToken,
66
- ...(isFormData ? body.getHeaders() : { 'Content-Type': 'application/json' }),
67
- },
68
- };
69
-
70
- console.log('[HTTP] Request:', method, url);
71
-
72
- const req = client.request(options, (res) => {
73
- let data = '';
74
- console.log('[HTTP] Response status:', res.statusCode);
75
-
76
- res.on('data', (chunk) => (data += chunk));
77
- res.on('end', () => {
78
- console.log('[HTTP] Raw response:', data);
79
- try {
80
- const json = JSON.parse(data);
81
- if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
82
- resolve(json);
83
- } else if (res.statusCode === 401 || res.statusCode === 403) {
84
- reject(new Error('认证失败,请检查租户Token配置'));
85
- } else if (res.statusCode === 404) {
86
- reject(new Error('上传服务路径不存在,请联系管理员'));
87
- } else {
88
- reject(new Error(`服务返回错误:${res.statusCode}`));
89
- }
90
- } catch (e) {
91
- console.error('[HTTP] Parse error:', e);
92
- console.error('[HTTP] Raw data:', data);
93
- reject(new Error('响应解析失败: ' + data));
94
- }
95
- });
75
+ method: 'POST',
76
+ headers: { ...this.authHeaders, ...form.getHeaders() },
96
77
  });
97
78
 
98
- req.on('error', (err) => {
99
- console.error('[HTTP] Request error:', err);
100
- reject(new Error(`网络错误:${err.message}`));
101
- });
79
+ this.handleResponse(req, resolve, reject);
80
+ req.on('error', (err) => reject(new Error(`网络错误:${err.message}`)));
81
+ form.pipe(req);
82
+ });
83
+ }
102
84
 
103
- if (body) {
104
- if (isFormData) {
105
- body.pipe(req);
106
- } else {
107
- req.write(JSON.stringify(body));
108
- }
109
- }
85
+ private request(method: string, url: string): Promise<any> {
86
+ return new Promise((resolve, reject) => {
87
+ const urlObj = new URL(url);
88
+ const client = urlObj.protocol === 'https:' ? https : http;
89
+
90
+ const req = client.request({
91
+ hostname: urlObj.hostname,
92
+ port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
93
+ path: urlObj.pathname,
94
+ method,
95
+ headers: { ...this.authHeaders, 'Content-Type': 'application/json' },
96
+ });
110
97
 
98
+ this.handleResponse(req, resolve, reject);
99
+ req.on('error', (err) => reject(new Error(`网络错误:${err.message}`)));
111
100
  req.end();
112
101
  });
113
102
  }
114
- }
103
+
104
+ private handleResponse(
105
+ req: http.ClientRequest,
106
+ resolve: (value: any) => void,
107
+ reject: (reason: any) => void
108
+ ): void {
109
+ req.on('response', (res) => {
110
+ let data = '';
111
+ res.on('data', (chunk) => (data += chunk));
112
+ res.on('end', () => {
113
+ console.log('[HTTP] Response:', res.statusCode, data.substring(0, 200));
114
+
115
+ try {
116
+ const json = JSON.parse(data);
117
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
118
+ resolve(json);
119
+ } else if (res.statusCode === 401 || res.statusCode === 403) {
120
+ reject(new Error('认证失败,请检查租户Token配置'));
121
+ } else if (res.statusCode === 404) {
122
+ reject(new Error('上传服务路径不存在,请联系管理员'));
123
+ } else {
124
+ reject(new Error(`服务返回错误:${res.statusCode}`));
125
+ }
126
+ } catch (e) {
127
+ reject(new Error('响应解析失败: ' + data.substring(0, 100)));
128
+ }
129
+ });
130
+ });
131
+ }
132
+ }