@fastcoder/vision-mcp-server 1.0.0

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.
Files changed (107) hide show
  1. package/README.md +263 -0
  2. package/README.zh-CN.md +210 -0
  3. package/build/core/api-common.d.ts +89 -0
  4. package/build/core/api-common.d.ts.map +1 -0
  5. package/build/core/api-common.js +119 -0
  6. package/build/core/api-common.js.map +1 -0
  7. package/build/core/base-image-service.d.ts +38 -0
  8. package/build/core/base-image-service.d.ts.map +1 -0
  9. package/build/core/base-image-service.js +92 -0
  10. package/build/core/base-image-service.js.map +1 -0
  11. package/build/core/chat-service.d.ts +42 -0
  12. package/build/core/chat-service.d.ts.map +1 -0
  13. package/build/core/chat-service.js +97 -0
  14. package/build/core/chat-service.js.map +1 -0
  15. package/build/core/environment.d.ts +76 -0
  16. package/build/core/environment.d.ts.map +1 -0
  17. package/build/core/environment.js +132 -0
  18. package/build/core/environment.js.map +1 -0
  19. package/build/core/error-handler.d.ts +124 -0
  20. package/build/core/error-handler.d.ts.map +1 -0
  21. package/build/core/error-handler.js +248 -0
  22. package/build/core/error-handler.js.map +1 -0
  23. package/build/core/file-service.d.ts +36 -0
  24. package/build/core/file-service.d.ts.map +1 -0
  25. package/build/core/file-service.js +141 -0
  26. package/build/core/file-service.js.map +1 -0
  27. package/build/index.d.ts +3 -0
  28. package/build/index.d.ts.map +1 -0
  29. package/build/index.js +119 -0
  30. package/build/index.js.map +1 -0
  31. package/build/prompts/data-viz.d.ts +5 -0
  32. package/build/prompts/data-viz.d.ts.map +1 -0
  33. package/build/prompts/data-viz.js +98 -0
  34. package/build/prompts/data-viz.js.map +1 -0
  35. package/build/prompts/diagram-analysis.d.ts +5 -0
  36. package/build/prompts/diagram-analysis.d.ts.map +1 -0
  37. package/build/prompts/diagram-analysis.js +102 -0
  38. package/build/prompts/diagram-analysis.js.map +1 -0
  39. package/build/prompts/error-diagnosis.d.ts +5 -0
  40. package/build/prompts/error-diagnosis.d.ts.map +1 -0
  41. package/build/prompts/error-diagnosis.js +69 -0
  42. package/build/prompts/error-diagnosis.js.map +1 -0
  43. package/build/prompts/general-image.d.ts +5 -0
  44. package/build/prompts/general-image.d.ts.map +1 -0
  45. package/build/prompts/general-image.js +45 -0
  46. package/build/prompts/general-image.js.map +1 -0
  47. package/build/prompts/index.d.ts +8 -0
  48. package/build/prompts/index.d.ts.map +1 -0
  49. package/build/prompts/index.js +8 -0
  50. package/build/prompts/index.js.map +1 -0
  51. package/build/prompts/text-extraction.d.ts +5 -0
  52. package/build/prompts/text-extraction.d.ts.map +1 -0
  53. package/build/prompts/text-extraction.js +45 -0
  54. package/build/prompts/text-extraction.js.map +1 -0
  55. package/build/prompts/ui-diff.d.ts +5 -0
  56. package/build/prompts/ui-diff.d.ts.map +1 -0
  57. package/build/prompts/ui-diff.js +190 -0
  58. package/build/prompts/ui-diff.js.map +1 -0
  59. package/build/prompts/ui-to-artifact.d.ts +10 -0
  60. package/build/prompts/ui-to-artifact.d.ts.map +1 -0
  61. package/build/prompts/ui-to-artifact.js +89 -0
  62. package/build/prompts/ui-to-artifact.js.map +1 -0
  63. package/build/tools/data-viz.d.ts +5 -0
  64. package/build/tools/data-viz.d.ts.map +1 -0
  65. package/build/tools/data-viz.js +93 -0
  66. package/build/tools/data-viz.js.map +1 -0
  67. package/build/tools/diagram-analysis.d.ts +5 -0
  68. package/build/tools/diagram-analysis.d.ts.map +1 -0
  69. package/build/tools/diagram-analysis.js +93 -0
  70. package/build/tools/diagram-analysis.js.map +1 -0
  71. package/build/tools/error-diagnosis.d.ts +5 -0
  72. package/build/tools/error-diagnosis.d.ts.map +1 -0
  73. package/build/tools/error-diagnosis.js +93 -0
  74. package/build/tools/error-diagnosis.js.map +1 -0
  75. package/build/tools/general-image.d.ts +5 -0
  76. package/build/tools/general-image.d.ts.map +1 -0
  77. package/build/tools/general-image.js +81 -0
  78. package/build/tools/general-image.js.map +1 -0
  79. package/build/tools/index.d.ts +8 -0
  80. package/build/tools/index.d.ts.map +1 -0
  81. package/build/tools/index.js +9 -0
  82. package/build/tools/index.js.map +1 -0
  83. package/build/tools/text-extraction.d.ts +5 -0
  84. package/build/tools/text-extraction.d.ts.map +1 -0
  85. package/build/tools/text-extraction.js +93 -0
  86. package/build/tools/text-extraction.js.map +1 -0
  87. package/build/tools/ui-diff.d.ts +5 -0
  88. package/build/tools/ui-diff.d.ts.map +1 -0
  89. package/build/tools/ui-diff.js +98 -0
  90. package/build/tools/ui-diff.js.map +1 -0
  91. package/build/tools/ui-to-artifact.d.ts +5 -0
  92. package/build/tools/ui-to-artifact.d.ts.map +1 -0
  93. package/build/tools/ui-to-artifact.js +117 -0
  94. package/build/tools/ui-to-artifact.js.map +1 -0
  95. package/build/types/index.d.ts +26 -0
  96. package/build/types/index.d.ts.map +1 -0
  97. package/build/types/index.js +43 -0
  98. package/build/types/index.js.map +1 -0
  99. package/build/utils/logger.d.ts +24 -0
  100. package/build/utils/logger.d.ts.map +1 -0
  101. package/build/utils/logger.js +119 -0
  102. package/build/utils/logger.js.map +1 -0
  103. package/build/utils/validation.d.ts +87 -0
  104. package/build/utils/validation.d.ts.map +1 -0
  105. package/build/utils/validation.js +155 -0
  106. package/build/utils/validation.js.map +1 -0
  107. package/package.json +70 -0
@@ -0,0 +1,248 @@
1
+ import { ApiError, ValidationError } from '../types/index.js';
2
+ /**
3
+ * Error severity levels
4
+ */
5
+ export var ErrorSeverity;
6
+ (function (ErrorSeverity) {
7
+ ErrorSeverity["LOW"] = "low";
8
+ ErrorSeverity["MEDIUM"] = "medium";
9
+ ErrorSeverity["HIGH"] = "high";
10
+ ErrorSeverity["CRITICAL"] = "critical";
11
+ })(ErrorSeverity || (ErrorSeverity = {}));
12
+ /**
13
+ * Error categories
14
+ */
15
+ export var ErrorCategory;
16
+ (function (ErrorCategory) {
17
+ ErrorCategory["VALIDATION"] = "validation";
18
+ ErrorCategory["AUTHENTICATION"] = "authentication";
19
+ ErrorCategory["AUTHORIZATION"] = "authorization";
20
+ ErrorCategory["NETWORK"] = "network";
21
+ ErrorCategory["API"] = "api";
22
+ ErrorCategory["SYSTEM"] = "system";
23
+ ErrorCategory["BUSINESS"] = "business";
24
+ ErrorCategory["UNKNOWN"] = "unknown";
25
+ })(ErrorCategory || (ErrorCategory = {}));
26
+ /**
27
+ * Base error class
28
+ */
29
+ export class BaseError extends Error {
30
+ code;
31
+ severity;
32
+ category;
33
+ context;
34
+ cause;
35
+ recoverable;
36
+ constructor(message, code, severity, category, context = {}, cause, recoverable = true) {
37
+ super(message);
38
+ this.name = this.constructor.name;
39
+ this.code = code;
40
+ this.severity = severity;
41
+ this.category = category;
42
+ this.context = {
43
+ timestamp: Date.now(),
44
+ ...context
45
+ };
46
+ this.cause = cause;
47
+ this.recoverable = recoverable;
48
+ // Preserve stack trace
49
+ if (Error.captureStackTrace) {
50
+ Error.captureStackTrace(this, this.constructor);
51
+ }
52
+ }
53
+ /**
54
+ * Convert to JSON format
55
+ */
56
+ toJSON() {
57
+ return {
58
+ name: this.name,
59
+ message: this.message,
60
+ code: this.code,
61
+ severity: this.severity,
62
+ category: this.category,
63
+ context: this.context,
64
+ recoverable: this.recoverable,
65
+ stack: this.stack,
66
+ cause: this.cause
67
+ ? {
68
+ name: this.cause.name,
69
+ message: this.cause.message,
70
+ stack: this.cause.stack
71
+ }
72
+ : undefined
73
+ };
74
+ }
75
+ /**
76
+ * Get user-friendly error message
77
+ */
78
+ getUserMessage() {
79
+ return this.message;
80
+ }
81
+ }
82
+ /**
83
+ * Business logic error
84
+ */
85
+ export class BusinessError extends BaseError {
86
+ constructor(message, code = 'BUSINESS_ERROR', context = {}, cause) {
87
+ super(message, code, ErrorSeverity.MEDIUM, ErrorCategory.BUSINESS, context, cause, true);
88
+ }
89
+ getUserMessage() {
90
+ return this.message;
91
+ }
92
+ }
93
+ /**
94
+ * System error
95
+ */
96
+ export class SystemError extends BaseError {
97
+ constructor(message, code = 'SYSTEM_ERROR', context = {}, cause) {
98
+ super(message, code, ErrorSeverity.HIGH, ErrorCategory.SYSTEM, context, cause, false);
99
+ }
100
+ getUserMessage() {
101
+ return 'An internal system error occurred. Please try again later.';
102
+ }
103
+ }
104
+ /**
105
+ * Network error
106
+ */
107
+ export class NetworkError extends BaseError {
108
+ constructor(message, code = 'NETWORK_ERROR', context = {}, cause) {
109
+ super(message, code, ErrorSeverity.MEDIUM, ErrorCategory.NETWORK, context, cause, true);
110
+ }
111
+ getUserMessage() {
112
+ return 'Network connection error. Please check your connection and try again.';
113
+ }
114
+ }
115
+ /**
116
+ * Authentication error
117
+ */
118
+ export class AuthenticationError extends BaseError {
119
+ constructor(message, code = 'AUTHENTICATION_ERROR', context = {}, cause) {
120
+ super(message, code, ErrorSeverity.HIGH, ErrorCategory.AUTHENTICATION, context, cause, false);
121
+ }
122
+ getUserMessage() {
123
+ return 'Authentication failed. Please check your credentials.';
124
+ }
125
+ }
126
+ /**
127
+ * Authorization error
128
+ */
129
+ export class AuthorizationError extends BaseError {
130
+ constructor(message, code = 'AUTHORIZATION_ERROR', context = {}, cause) {
131
+ super(message, code, ErrorSeverity.HIGH, ErrorCategory.AUTHORIZATION, context, cause, false);
132
+ }
133
+ getUserMessage() {
134
+ return 'Access denied. You do not have permission to perform this action.';
135
+ }
136
+ }
137
+ /**
138
+ * Tool execution error
139
+ */
140
+ export class ToolExecutionError extends BaseError {
141
+ toolName;
142
+ constructor(message, toolName, code = 'TOOL_EXECUTION_ERROR', context = {}, cause) {
143
+ super(message, code, ErrorSeverity.MEDIUM, ErrorCategory.BUSINESS, { ...context, toolName }, cause, true);
144
+ this.toolName = toolName;
145
+ }
146
+ getUserMessage() {
147
+ return `Tool execution failed: ${this.message}`;
148
+ }
149
+ }
150
+ /**
151
+ * Default error handling strategy
152
+ */
153
+ class DefaultErrorHandlingStrategy {
154
+ canHandle(_error) {
155
+ return true; // Default strategy handles all errors
156
+ }
157
+ async handle(error, context) {
158
+ // If already a standardized error, return directly
159
+ if (error instanceof BaseError) {
160
+ return error;
161
+ }
162
+ // Handle known error types
163
+ if (error instanceof ValidationError) {
164
+ return new BusinessError(error.message, 'VALIDATION_ERROR', context, error);
165
+ }
166
+ if (error instanceof ApiError) {
167
+ return new SystemError(error.message, 'API_ERROR', context, error);
168
+ }
169
+ // Handle unknown errors
170
+ return new SystemError(error.message || 'An unknown error occurred', 'UNKNOWN_ERROR', context, error);
171
+ }
172
+ }
173
+ /**
174
+ * Network error handling strategy
175
+ */
176
+ class NetworkErrorHandlingStrategy {
177
+ canHandle(error) {
178
+ return (error.message.includes('network') ||
179
+ error.message.includes('timeout') ||
180
+ error.message.includes('connection') ||
181
+ error.name === 'NetworkError');
182
+ }
183
+ async handle(error, context) {
184
+ return new NetworkError(error.message, 'NETWORK_CONNECTION_ERROR', context, error instanceof Error ? error : undefined);
185
+ }
186
+ }
187
+ /**
188
+ * Unified error handler
189
+ */
190
+ export class ErrorHandler {
191
+ strategies = [];
192
+ constructor() {
193
+ // Register strategies in order
194
+ this.addStrategy(new NetworkErrorHandlingStrategy());
195
+ this.addStrategy(new DefaultErrorHandlingStrategy()); // Default strategy goes last
196
+ }
197
+ /**
198
+ * Add error handling strategy
199
+ */
200
+ addStrategy(strategy) {
201
+ this.strategies.push(strategy);
202
+ }
203
+ /**
204
+ * Handle error
205
+ */
206
+ async handleError(error, context = {}) {
207
+ const errorContext = {
208
+ timestamp: Date.now(),
209
+ ...context
210
+ };
211
+ try {
212
+ // Find appropriate handling strategy
213
+ const strategy = this.strategies.find(s => s.canHandle(error));
214
+ if (!strategy) {
215
+ console.warn('No suitable error handling strategy found', {
216
+ error: error.message
217
+ });
218
+ return new SystemError('No error handler available', 'NO_HANDLER_ERROR', errorContext, error instanceof Error ? error : undefined);
219
+ }
220
+ // Handle error
221
+ const standardError = await strategy.handle(error, errorContext);
222
+ console.error('Error handled', {
223
+ name: standardError.name,
224
+ message: standardError.message,
225
+ code: standardError.code
226
+ });
227
+ return standardError;
228
+ }
229
+ catch (handlingError) {
230
+ console.error('Failed to handle error', {
231
+ originalError: error.message,
232
+ handlingError: handlingError instanceof Error ? handlingError.message : String(handlingError)
233
+ });
234
+ return new SystemError('Error handling failed', 'HANDLING_ERROR', errorContext, handlingError instanceof Error ? handlingError : undefined);
235
+ }
236
+ }
237
+ }
238
+ /**
239
+ * Global error handler instance
240
+ */
241
+ export const errorHandler = new ErrorHandler();
242
+ /**
243
+ * Convenience function to handle errors
244
+ */
245
+ export async function handleError(error, context = {}) {
246
+ return errorHandler.handleError(error, context);
247
+ }
248
+ //# sourceMappingURL=error-handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../src/core/error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAE9D;;GAEG;AACH,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,4BAAW,CAAA;IACX,kCAAiB,CAAA;IACjB,8BAAa,CAAA;IACb,sCAAqB,CAAA;AACvB,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,aASX;AATD,WAAY,aAAa;IACvB,0CAAyB,CAAA;IACzB,kDAAiC,CAAA;IACjC,gDAA+B,CAAA;IAC/B,oCAAmB,CAAA;IACnB,4BAAW,CAAA;IACX,kCAAiB,CAAA;IACjB,sCAAqB,CAAA;IACrB,oCAAmB,CAAA;AACrB,CAAC,EATW,aAAa,KAAb,aAAa,QASxB;AAUD;;GAEG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAClB,IAAI,CAAS;IACb,QAAQ,CAAgB;IACxB,QAAQ,CAAgB;IACxB,OAAO,CAAe;IACtB,KAAK,CAAS;IACd,WAAW,CAAU;IAErC,YACE,OAAe,EACf,IAAY,EACZ,QAAuB,EACvB,QAAuB,EACvB,UAAiC,EAAE,EACnC,KAAa,EACb,cAAuB,IAAI;QAE3B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf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,IAAI,YAAY,EAAE,CAAC;AAE/C;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,KAAwB,EACxB,UAAiC,EAAE;IAEnC,OAAO,YAAY,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * File operations service (images only - video methods removed)
3
+ */
4
+ export declare class FileService {
5
+ /**
6
+ * Check if a string is a URL
7
+ */
8
+ static isUrl(source: string): boolean;
9
+ /**
10
+ * Validate if image source exists and check size limit
11
+ * @param imageSource Path to image file or URL
12
+ * @param maxSizeMB Maximum file size in MB (default: 20MB for OpenAI)
13
+ */
14
+ static validateImageSource(imageSource: string, maxSizeMB?: number): Promise<void>;
15
+ /**
16
+ * Encode image to base64 data URL (from file or URL)
17
+ * @param imageSource Path to image file or URL
18
+ * @returns Base64 encoded image data
19
+ */
20
+ static encodeImageToBase64(imageSource: string): Promise<string>;
21
+ /**
22
+ * Download image from URL and encode to base64
23
+ * @param imageUrl Image URL to download
24
+ * @returns Base64 encoded image data
25
+ */
26
+ private static downloadAndEncodeImage;
27
+ /**
28
+ * Get MIME type for image file extension or content type
29
+ */
30
+ static getMimeType(extension: string): string;
31
+ }
32
+ /**
33
+ * File service for image operations
34
+ */
35
+ export declare const fileService: typeof FileService;
36
+ //# sourceMappingURL=file-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-service.d.ts","sourceRoot":"","sources":["../../src/core/file-service.ts"],"names":[],"mappings":"AAIA;;GAEG;AACH,qBAAa,WAAW;IACtB;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IASrC;;;;OAIG;WACU,mBAAmB,CAC9B,WAAW,EAAE,MAAM,EACnB,SAAS,GAAE,MAAW,GACrB,OAAO,CAAC,IAAI,CAAC;IA+ChB;;;;OAIG;WACU,mBAAmB,CAC9B,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,CAAC;IAelB;;;;OAIG;mBACkB,sBAAsB;IA6D3C;;OAEG;IACH,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM;CAU9C;AAED;;GAEG;AACH,eAAO,MAAM,WAAW,oBAAc,CAAC"}
@@ -0,0 +1,141 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { FileNotFoundError, ValidationError } from '../types/index.js';
4
+ /**
5
+ * File operations service (images only - video methods removed)
6
+ */
7
+ export class FileService {
8
+ /**
9
+ * Check if a string is a URL
10
+ */
11
+ static isUrl(source) {
12
+ try {
13
+ const url = new URL(source);
14
+ return url.protocol === 'http:' || url.protocol === 'https:';
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ /**
21
+ * Validate if image source exists and check size limit
22
+ * @param imageSource Path to image file or URL
23
+ * @param maxSizeMB Maximum file size in MB (default: 20MB for OpenAI)
24
+ */
25
+ static async validateImageSource(imageSource, maxSizeMB = 20) {
26
+ if (this.isUrl(imageSource)) {
27
+ // For URLs, validate URL format
28
+ try {
29
+ const url = new URL(imageSource);
30
+ if (!['http:', 'https:'].includes(url.protocol)) {
31
+ throw new ValidationError(`Unsupported URL protocol: ${url.protocol}. Only http:// and https:// are supported.`);
32
+ }
33
+ }
34
+ catch (error) {
35
+ if (error instanceof ValidationError) {
36
+ throw error;
37
+ }
38
+ throw new ValidationError(`Invalid URL format: ${imageSource}. Error: ${error instanceof Error ? error.message : String(error)}`);
39
+ }
40
+ // Note: Actual content validation (size, format) happens during download in encodeImageToBase64
41
+ return;
42
+ }
43
+ if (!fs.existsSync(imageSource)) {
44
+ throw new FileNotFoundError(`Image file not found: ${imageSource}`);
45
+ }
46
+ const stats = fs.statSync(imageSource);
47
+ const maxSizeBytes = maxSizeMB * 1024 * 1024;
48
+ if (stats.size > maxSizeBytes) {
49
+ throw new ValidationError(`Image file too large: ${(stats.size / (1024 * 1024)).toFixed(2)}MB. ` +
50
+ `Maximum allowed: ${maxSizeMB}MB`);
51
+ }
52
+ const ext = path.extname(imageSource).toLowerCase();
53
+ const supportedExts = ['.jpg', '.jpeg', '.png'];
54
+ if (!supportedExts.includes(ext)) {
55
+ throw new ValidationError(`Unsupported image format: ${ext}. ` +
56
+ `Supported formats: ${supportedExts.join(', ')}`);
57
+ }
58
+ }
59
+ /**
60
+ * Encode image to base64 data URL (from file or URL)
61
+ * @param imageSource Path to image file or URL
62
+ * @returns Base64 encoded image data
63
+ */
64
+ static async encodeImageToBase64(imageSource) {
65
+ if (this.isUrl(imageSource)) {
66
+ // For URLs, download and encode to base64
67
+ return this.downloadAndEncodeImage(imageSource);
68
+ }
69
+ // For local files, encode to base64
70
+ const imageBuffer = fs.readFileSync(imageSource);
71
+ const ext = path.extname(imageSource).toLowerCase().slice(1);
72
+ const mimeType = this.getMimeType(ext);
73
+ console.debug('Encoded image to base64', { imageSource, mimeType });
74
+ return `data:${mimeType};base64,${imageBuffer.toString('base64')}`;
75
+ }
76
+ /**
77
+ * Download image from URL and encode to base64
78
+ * @param imageUrl Image URL to download
79
+ * @returns Base64 encoded image data
80
+ */
81
+ static async downloadAndEncodeImage(imageUrl) {
82
+ console.debug('Downloading image from URL', { imageUrl });
83
+ try {
84
+ const response = await fetch(imageUrl);
85
+ if (!response.ok) {
86
+ throw new ValidationError(`Failed to download image: HTTP ${response.status} ${response.statusText}`);
87
+ }
88
+ // Get content type from response headers
89
+ const contentType = response.headers.get('content-type');
90
+ if (!contentType || !contentType.startsWith('image/')) {
91
+ throw new ValidationError(`Invalid content type: ${contentType}. Expected image/*`);
92
+ }
93
+ // Get content length for size validation
94
+ const contentLength = response.headers.get('content-length');
95
+ if (contentLength) {
96
+ const sizeInMB = parseInt(contentLength) / (1024 * 1024);
97
+ if (sizeInMB > 20) {
98
+ throw new ValidationError(`Downloaded image too large: ${sizeInMB.toFixed(2)}MB. Maximum allowed: 20MB`);
99
+ }
100
+ }
101
+ // Download image data
102
+ const imageBuffer = Buffer.from(await response.arrayBuffer());
103
+ // Additional size check from actual data
104
+ const actualSizeInMB = imageBuffer.length / (1024 * 1024);
105
+ if (actualSizeInMB > 20) {
106
+ throw new ValidationError(`Downloaded image too large: ${actualSizeInMB.toFixed(2)}MB. Maximum allowed: 20MB`);
107
+ }
108
+ console.debug('Successfully downloaded and encoded image', {
109
+ imageUrl,
110
+ contentType,
111
+ sizeInMB: actualSizeInMB.toFixed(2)
112
+ });
113
+ return `data:${contentType};base64,${imageBuffer.toString('base64')}`;
114
+ }
115
+ catch (error) {
116
+ if (error instanceof ValidationError) {
117
+ throw error;
118
+ }
119
+ throw new ValidationError(`Failed to download image from URL: ${imageUrl}. ` +
120
+ `Error: ${error instanceof Error ? error.message : String(error)}`);
121
+ }
122
+ }
123
+ /**
124
+ * Get MIME type for image file extension or content type
125
+ */
126
+ static getMimeType(extension) {
127
+ const mimeTypes = {
128
+ png: 'image/png',
129
+ jpg: 'image/jpeg',
130
+ jpeg: 'image/jpeg',
131
+ webp: 'image/webp',
132
+ gif: 'image/gif'
133
+ };
134
+ return mimeTypes[extension] || 'image/png';
135
+ }
136
+ }
137
+ /**
138
+ * File service for image operations
139
+ */
140
+ export const fileService = FileService;
141
+ //# sourceMappingURL=file-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-service.js","sourceRoot":"","sources":["../../src/core/file-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEvE;;GAEG;AACH,MAAM,OAAO,WAAW;IACtB;;OAEG;IACH,MAAM,CAAC,KAAK,CAAC,MAAc;QACzB,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;YAC5B,OAAO,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,GAAG,CAAC,QAAQ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xB,MAAM,IAAI,eAAe,CACvB,+BAA+B,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC,2BAA2B,CACpF,CAAC;YACJ,CAAC;YAED,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE;gBACzD,QAAQ;gBACR,WAAW;gBACX,QAAQ,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;aACpC,CAAC,CAAC;YAEH,OAAO,QAAQ,WAAW,WAAW,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,eAAe,EAAE,CAAC;gBACrC,MAAM,KAAK,CAAC;YACd,CAAC;YACD,MAAM,IAAI,eAAe,CACvB,sCAAsC,QAAQ,IAAI;gBAClD,UAAU,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CACnE,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,WAAW,CAAC,SAAiB;QAClC,MAAM,SAAS,GAA2B;YACxC,GAAG,EAAE,WAAW;YAChB,GAAG,EAAE,YAAY;YACjB,IAAI,EAAE,YAAY;YAClB,IAAI,EAAE,YAAY;YAClB,GAAG,EAAE,WAAW;SACjB,CAAC;QACF,OAAO,SAAS,CAAC,SAAS,CAAC,IAAI,WAAW,CAAC;IAC7C,CAAC;CACF;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,WAAW,CAAC"}
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/build/index.js ADDED
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { configurationService } from './core/environment.js';
5
+ import { handleError } from './core/error-handler.js';
6
+ import { setupConsoleRedirection } from './utils/logger.js';
7
+ // Import tool registration functions
8
+ import { registerUiToArtifactTool } from './tools/ui-to-artifact.js';
9
+ import { registerTextExtractionTool } from './tools/text-extraction.js';
10
+ import { registerErrorDiagnosisTool } from './tools/error-diagnosis.js';
11
+ import { registerDiagramAnalysisTool } from './tools/diagram-analysis.js';
12
+ import { registerDataVizAnalysisTool } from './tools/data-viz.js';
13
+ import { registerUiDiffCheckTool } from './tools/ui-diff.js';
14
+ import { registerGeneralImageAnalysisTool } from './tools/general-image.js';
15
+ /**
16
+ * MCP Server Application class
17
+ */
18
+ class McpServerApplication {
19
+ server;
20
+ constructor() {
21
+ this.server = new McpServer({
22
+ name: configurationService.getServerConfig().name,
23
+ version: configurationService.getServerConfig().version
24
+ }, {
25
+ capabilities: {
26
+ tools: {}
27
+ }
28
+ });
29
+ this.setupErrorHandling();
30
+ console.info('MCP Server Application initialized');
31
+ }
32
+ /**
33
+ * Setup error handling
34
+ */
35
+ setupErrorHandling() {
36
+ // Note: McpServer from @modelcontextprotocol/sdk does not have onerror property
37
+ // Error handling is managed by the server internally
38
+ process.on('SIGINT', () => {
39
+ console.info('Received SIGINT, shutting down gracefully...');
40
+ this.shutdown();
41
+ });
42
+ }
43
+ /**
44
+ * Register all tools
45
+ */
46
+ async registerTools() {
47
+ try {
48
+ // Register specialized image analysis tools (7 tools)
49
+ registerUiToArtifactTool(this.server);
50
+ registerTextExtractionTool(this.server);
51
+ registerErrorDiagnosisTool(this.server);
52
+ registerDiagramAnalysisTool(this.server);
53
+ registerDataVizAnalysisTool(this.server);
54
+ registerUiDiffCheckTool(this.server);
55
+ registerGeneralImageAnalysisTool(this.server);
56
+ console.info('Successfully registered all image analysis tools (7 tools)');
57
+ }
58
+ catch (error) {
59
+ const standardError = await handleError(error instanceof Error ? error : new Error(String(error)), {
60
+ operation: 'tool-registration',
61
+ metadata: { component: 'McpServerApplication' }
62
+ });
63
+ console.error('Failed to register tools', standardError);
64
+ throw standardError;
65
+ }
66
+ }
67
+ /**
68
+ * Start the server
69
+ */
70
+ async start() {
71
+ try {
72
+ await this.registerTools();
73
+ console.info('Starting Vision MCP Server...', {
74
+ name: configurationService.getServerConfig().name,
75
+ version: configurationService.getServerConfig().version
76
+ });
77
+ const transport = new StdioServerTransport();
78
+ await this.server.connect(transport);
79
+ console.info('Vision MCP Server is running');
80
+ }
81
+ catch (error) {
82
+ const standardError = await handleError(error instanceof Error ? error : new Error(String(error)), {
83
+ operation: 'server-start',
84
+ metadata: { component: 'McpServerApplication' }
85
+ });
86
+ console.error('Failed to start server', standardError);
87
+ throw standardError;
88
+ }
89
+ }
90
+ /**
91
+ * Shutdown the server
92
+ */
93
+ async shutdown() {
94
+ try {
95
+ await this.server.close();
96
+ console.info('Server shutdown complete');
97
+ process.exit(0);
98
+ }
99
+ catch (error) {
100
+ console.error('Error during shutdown', { error });
101
+ process.exit(1);
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Main entry point
107
+ */
108
+ async function main() {
109
+ // Setup console redirection BEFORE any other code to prevent stdout pollution
110
+ setupConsoleRedirection();
111
+ const app = new McpServerApplication();
112
+ await app.start();
113
+ }
114
+ // Start the application
115
+ main().catch(error => {
116
+ console.error('Fatal error:', error);
117
+ process.exit(1);
118
+ });
119
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,uBA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,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EACzD;gBACE,SAAS,EAAE,cAAc;gBACzB,QAAQ,EAAE,EAAE,SAAS,EAAE,sBAAsB,EAAE;aAChD,CACF,CAAC;YACF,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,aAAa,CAAC,CAAC;YACvD,MAAM,aAAa,CAAC;QACtB,CAAC;IACH,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,QAAQ;QACpB,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAC1B,OAAO,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;YACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,uBAAuB,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;CACF;AAED;;GAEG;AACH,KAAK,UAAU,IAAI;IACjB,8EAA8E;IAC9E,uBAAuB,EAAE,CAAC;IAE1B,MAAM,GAAG,GAAG,IAAI,oBAAoB,EAAE,CAAC;IACvC,MAAM,GAAG,CAAC,KAAK,EAAE,CAAC;AACpB,CAAC;AAED,wBAAwB;AACxB,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Data Visualization Analysis system prompt (Version 2)
3
+ */
4
+ export declare const DATA_VIZ_ANALYSIS_PROMPT = "You are a data analyst with expertise in interpreting data visualizations and extracting meaningful insights. When you look at a chart or dashboard, you see beyond the visual representation\u2014you understand the story the data tells, recognize significant patterns and trends, identify anomalies that warrant attention, and can translate quantitative information into actionable insights.\n\n<task>\nYour task is to analyze the provided data visualization and extract meaningful insights, trends, patterns, and actionable recommendations. Your analysis should help decision-makers understand what the data reveals, what it means for their context, and what actions they might consider based on these insights.\n</task>\n\n<approach>\nBegin by understanding what you're looking at. Identify the type of visualization\u2014is it a line chart showing trends over time, a bar chart comparing categories, a pie chart showing proportions, a scatter plot revealing correlations, a heatmap displaying intensity across dimensions, or something more complex like a combination dashboard? The visualization type tells you what kind of insights it's designed to convey.\n\nRead all the labels and annotations carefully. The title often states what's being measured. Axis labels define the dimensions\u2014what's on the x-axis and what's on the y-axis? What units are used? Are we looking at dollars, percentages, counts, rates? The legend explains what different colors, lines, or symbols represent, especially when comparing multiple data series. Any text annotations or callouts highlight specific points of interest that the visualization creator thought important.\n\nNote the time period or categories being displayed. Are we looking at data from the past week, month, year, or longer? Is it showing historical data, current state, or predictions? For categorical data, what categories are being compared? Understanding the temporal or categorical scope helps contextualize the insights.\n\nExtract the key metrics and values systematically. What are the maximum and minimum values shown? What's the current or most recent value? Can you identify average or typical values? Look for specific data points that are labeled or emphasized. In a dashboard with multiple metrics, note the relationship between different measurements.\n\nIdentify trends and patterns. For time-series data, is the overall trend upward, downward, or stable? Is the rate of change accelerating or decelerating? Are there cyclical patterns or seasonality\u2014does the data show regular peaks and troughs at predictable intervals? For comparative data, which categories or segments perform best or worst? Are there significant disparities between groups?\n\nLook for anomalies and interesting deviations. Are there sudden spikes or drops that break the normal pattern? Are there outliers\u2014data points that don't fit the general distribution? Sometimes these anomalies are the most important insight\u2014a spike might indicate a successful campaign or a system issue; a drop might signal a problem or changing market conditions.\n\nConsider what might cause the patterns you observe. If revenue increased sharply in December, that might be expected seasonality for retail. If server response times spiked at 3 AM on Tuesday, that might indicate a batch job or an attack. If certain user segments show higher engagement, what characteristics do they share? While you're analyzing a visualization, not raw data, you can still reason about likely causes based on common patterns and domain knowledge.\n\nThink about the implications and what actions the data might suggest. If a metric is trending negatively, what might help reverse it? If a particular segment is performing exceptionally well, should resources be directed there? If there's a concerning anomaly, what investigation or immediate action might be warranted? Connect the data patterns to decisions.\n\nAssess the data quality and completeness visible in the visualization. Are there gaps in the timeline suggesting missing data? Do any values seem unrealistic or impossible? Are there notes about data collection issues? Being aware of potential data quality issues helps qualify your insights appropriately.\n\nIf comparing multiple metrics or data series, look for correlations and relationships. Do two metrics move together, suggesting they're related? Does one seem to lead to another, suggesting causation? Are there trade-offs visible where improving one metric seems to worsen another?\n\nConsider what additional information might be needed for a more complete analysis. Sometimes a visualization raises as many questions as it answers. Noting what you'd want to investigate further demonstrates analytical depth.\n</approach>\n\n<output_structure>\nStructure your analysis to be immediately useful for decision-making:\n\nBegin with a **Visualization Summary** that orients the reader. Describe what type of visualization this is and what it's measuring: \"This is a multi-line chart showing website traffic metrics over the past 90 days, comparing page views, unique visitors, and session duration.\" Identify the time period or scope: \"The data spans from January 1 to March 31, 2024.\" Note any data sources if visible: \"The data appears to be from Google Analytics based on the interface styling.\"\n\nIn the **Key Metrics** section, extract and present the important numbers clearly:\n\n\"Current Metrics (as of March 31, 2024):\n|- Page Views: 1.2M (up from 950K at start of period, +26% growth)\n|- Unique Visitors: 285K (up from 230K, +24% growth)\n|- Average Session Duration: 4:32 minutes (down from 5:10, -12% decline)\n\nPeak Values:\n|- Highest single-day page views: 52K on March 15\n|- Highest unique visitors: 12K on March 15\n|- Longest average session: 6:15 on January 8\n\nNotable Comparisons:\n|- March averaged 40K daily page views vs. January's 31K average (+29%)\n|- Weekend traffic consistently lower than weekdays (approximately 30% reduction)\n|- Mobile visitors account for approximately 60% of total based on segmentation visible in the dashboard\"\n\nIn the **Trends & Patterns** section, describe what the data reveals over time or across categories:\n\n\"The visualization shows several clear trends:\n\nOverall Growth: Both page views and unique visitors display consistent upward trajectories throughout the period, with month-over-month acceleration. The growth appears strongest in March, suggesting increasing traction or the impact of recent initiatives.\n\nCyclical Patterns: There's a pronounced weekly pattern with traffic peaking mid-week (Tuesday through Thursday) and declining on weekends. This suggests a business or professional audience rather than consumer entertainment use.\n\nSeasonality Shift: The data shows a notable inflection point around February 20, where the growth rate accelerates. This aligns with the end of the typical holiday slowdown and might indicate the start of a busy business season or the launch of a new marketing campaign.\n\nEngagement Concern: While visit metrics trend upward, session duration trends downward. This inverse relationship suggests that while more people are coming to the site, they're spending less time per visit on average. This could indicate either that users are finding what they need more quickly (positive) or that content engagement is declining (concerning).\"\n\nIn the **Anomalies & Insights** section, highlight unusual observations and what they might mean:\n\n\"Several anomalies warrant attention:\n\nMarch 15 Spike: Traffic on March 15 exceeded normal levels by approximately 150%. This spike in both page views and unique visitors suggests an external event\u2014perhaps a media mention, social media viral post, or successful marketing campaign. Investigating what happened that day could reveal replicable success factors.\n\nJanuary 8 Engagement Peak: While January saw lower traffic volumes, session duration peaked at over 6 minutes. The content or user behavior that day might offer insights into what drives deeper engagement.\n\nWeekend Gaps: The consistent and significant weekend traffic decline suggests that the primary audience is professional users accessing during work hours. This has implications for support staffing, deployment timing, and content publishing schedules.\n\nLate March Volatility: The last week of March shows increased day-to-day variance in all metrics compared to earlier months. This could indicate a shift in traffic sources (perhaps from referrals or ads rather than organic search), or might reflect data collection issues that should be verified.\"\n\nIn the **Actionable Recommendations** section, translate insights into suggested actions:\n\n\"Based on this analysis, consider the following actions:\n\nInvestigate Session Duration Decline: The 12% drop in engagement time despite 26% traffic growth is concerning and deserves immediate investigation. Analyze which pages have decreasing time-on-page, review recent content or design changes that might reduce engagement, and examine whether new traffic sources bring less engaged visitors.\n\nCapitalize on Mid-Week Peak: Since traffic peaks mid-week, schedule important announcements, product launches, or content publications for Tuesday-Thursday to maximize visibility and impact.\n\nStudy March 15 Success: Conduct a detailed post-mortem on what drove the March 15 traffic spike. If it was a specific campaign, content piece, or external mention, try to replicate the success factors.\n\nOptimize for Professional Audience: The weekday traffic pattern confirms a professional user base. Tailor content strategy, support hours, and communication timing to this audience's work schedule.\n\nMonitor New Visitor Conversion: With unique visitors growing at nearly the same rate as page views, the pages-per-visitor ratio remains relatively flat. Consider strategies to improve new visitor engagement and encourage deeper exploration of the site\u2014perhaps through better internal linking, more compelling related content suggestions, or clearer navigation paths.\n\nAddress Late March Volatility: If the increased variance continues into April, investigate potential causes such as changes in traffic sources, technical issues affecting measurement, or external market factors affecting audience behavior.\"\n</output_structure>\n\nYour analysis should transform raw visualizations into actionable intelligence, making data accessible and meaningful for decision-makers who need to understand not just what the numbers are, but what they mean and what to do about them.";
5
+ //# sourceMappingURL=data-viz.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-viz.d.ts","sourceRoot":"","sources":["../../src/prompts/data-viz.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,wBAAwB,s4UA6FyM,CAAC"}