luma-mcp 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -191,26 +191,27 @@ npm run test:local https://example.com/image.jpg
191
191
  - 支持格式: JPG, PNG, WebP, GIF
192
192
  - 本地文件: 绝对路径或相对路径
193
193
  - 远程图片: https:// 开头的 URL
194
- - `question` (可选): 关于图片的问题或分析指令
194
+ - `prompt` (必需): 分析指令或问题
195
195
 
196
196
  **示例**:
197
197
 
198
198
  ```typescript
199
199
  // 通用分析
200
200
  analyze_image({
201
- image_source: "./screenshot.png"
201
+ image_source: "./screenshot.png",
202
+ prompt: "请详细分析这张图片的内容"
202
203
  })
203
204
 
204
205
  // 代码分析
205
206
  analyze_image({
206
207
  image_source: "./code-error.png",
207
- question: "这段代码为什么报错?请提供修复建议"
208
+ prompt: "这段代码为什么报错?请提供修复建议"
208
209
  })
209
210
 
210
211
  // UI 分析
211
212
  analyze_image({
212
213
  image_source: "https://example.com/ui.png",
213
- question: "分析这个界面的布局和可用性问题"
214
+ prompt: "分析这个界面的布局和可用性问题"
214
215
  })
215
216
  ```
216
217
 
@@ -223,9 +224,26 @@ analyze_image({
223
224
  | `ZHIPU_MAX_TOKENS` | 否 | `4096` | 最大生成 tokens |
224
225
  | `ZHIPU_TEMPERATURE` | 否 | `0.7` | 温度参数 (0-1) |
225
226
  | `ZHIPU_TOP_P` | 否 | `0.7` | Top-p 参数 (0-1) |
226
- | `ZHIPU_ENABLE_THINKING` | 否 | `false` | 是否强制启用思考模式 |
227
-
228
- 注意: 思考模式默认已启用,无需额外配置。
227
+ | `ZHIPU_ENABLE_THINKING` | 否 | `true` | 是否启用思考模式 |
228
+
229
+ **思考模式说明**:
230
+ - 默认开启,提高图片分析的准确性和详细程度
231
+ - 如需关闭(提高速度、降低成本),请在配置文件中设置:
232
+ ```json
233
+ {
234
+ "mcpServers": {
235
+ "luma": {
236
+ "command": "npx",
237
+ "args": ["-y", "luma-mcp"],
238
+ "env": {
239
+ "ZHIPU_API_KEY": "your-api-key",
240
+ "ZHIPU_ENABLE_THINKING": "false"
241
+ }
242
+ }
243
+ }
244
+ }
245
+ ```
246
+ - 关闭后可节省 20-30% tokens 消耗,响应速度提升约 30%
229
247
 
230
248
  ## 开发
231
249
 
@@ -317,8 +335,6 @@ MIT License
317
335
  - [智谱 AI 开放平台](https://open.bigmodel.cn/)
318
336
  - [GLM-4.5V 文档](https://docs.bigmodel.cn/cn/guide/models/vlm/glm-4.5v)
319
337
  - [MCP 协议文档](https://modelcontextprotocol.io/)
320
- - [设计文档](./docs/design.md)
321
- - [安装配置指南](./docs/installation.md)
322
338
 
323
339
  ## 作者
324
340
 
@@ -38,10 +38,10 @@ export class ZhipuClient {
38
38
  temperature: this.config.temperature,
39
39
  max_tokens: this.config.maxTokens,
40
40
  top_p: this.config.topP,
41
- thinking: { type: 'enabled' }, // 默认启用 thinking
41
+ thinking: { type: 'enabled' }, // 默认启用思考模式,提高分析准确性
42
42
  };
43
- // 允许显式禁用 thinking
44
- if (enableThinking === false) {
43
+ // 允许显式禁用 thinking(如需要更快速度)
44
+ if (this.config.enableThinking === false || enableThinking === false) {
45
45
  delete requestBody.thinking;
46
46
  }
47
47
  logger.info('Calling GLM-4.5V API', {
@@ -1 +1 @@
1
- {"version":3,"file":"zhipu-client.js","sourceRoot":"","sources":["../src/zhipu-client.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AA2C3C;;GAEG;AACH,MAAM,OAAO,WAAW;IACd,MAAM,CAAa;IACnB,WAAW,GAAG,uDAAuD,CAAC;IAE9E,YAAY,MAAkB;QAC5B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,YAAY,CAAC,YAAoB,EAAE,MAAc,EAAE,cAAwB;Q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@
1
1
  {
2
2
  "name": "luma-mcp",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "A vision understanding MCP server powered by GLM-4.5V",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,10 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "mcp__devmind__list_projects",
5
- "mcp__time__current_time"
6
- ],
7
- "deny": [],
8
- "ask": []
9
- }
10
- }
@@ -1,41 +0,0 @@
1
- # ZAI MCP Server
2
-
3
- [中文文档](https://docs.bigmodel.cn/cn/coding-plan/mcp/vision-mcp-server) | [English Document](https://docs.z.ai/devpack/mcp/vision-mcp-server)
4
-
5
-
6
- A Model Context Protocol (MCP) server that provides AI capabilities powered by Z.AI.
7
-
8
- ## Environment Variables
9
-
10
- - `Z_AI_MODE` - The platform to use for AI services (default: `ZHIPU`) ZHIPU or ZAI
11
- - `Z_AI_API_KEY` - Your API key
12
-
13
- For ZAI: Use ZAI platform https://z.ai/model-api
14
-
15
- For ZHIPU: Use Zhipu AI platform https://bigmodel.cn
16
-
17
- ## Usage
18
-
19
- ### Use this MCP Server in Claude Code
20
-
21
- It is recommended to use the version Node.js 18+, Claude Code 2.0.14+.
22
-
23
- **Note**: You need to configure `Z_AI_MODE` as `ZAI` or `ZHIPU` depending on the platform.
24
-
25
- For ZAI Use,
26
-
27
- ```shell
28
- claude mcp add zai-mcp-server --env Z_AI_API_KEY=your_api_key Z_AI_MODE=ZAI -- npx -y "@z_ai/mcp-server"
29
- ```
30
-
31
- For ZHIPU Use,
32
-
33
- ```shell
34
- claude mcp add zai-mcp-server --env Z_AI_API_KEY=your_api_key Z_AI_MODE=ZHIPU -- npx -y "@z_ai/mcp-server"
35
- ```
36
-
37
- ### Use this MCP Server in Others MCP Client
38
-
39
- For Z.ai Use, refer the [Vision MCP Doc](https://docs.z.ai/devpack/mcp/vision-mcp-server)
40
-
41
- For ZhiPU Use, refer the [Vision MCP Doc](https://docs.bigmodel.cn/cn/coding-plan/mcp/vision-mcp-server)
@@ -1,42 +0,0 @@
1
- # ZAI MCP 服务器
2
-
3
- [中文文档](https://docs.bigmodel.cn/cn/coding-plan/mcp/vision-mcp-server) | [English Document](https://docs.z.ai/devpack/mcp/vision-mcp-server)
4
-
5
- 一个基于 Z.AI 提供 AI 能力的模型上下文协议 (MCP) 服务器。
6
-
7
- ## MCP 工具
8
-
9
- 该服务器实现了模型上下文协议,可与任何兼容 MCP 的客户端一起使用。服务器提供以下工具:
10
-
11
- - `image_analysis` - 分析图像并提供详细描述
12
- - `video_analysis` - 分析视频并提供详细描述
13
-
14
- ## 环境变量
15
-
16
- - `Z_AI_MODE` - 用于 AI 服务的平台(默认:`ZHIPU`)ZHIPU 或 ZAI
17
- - `Z_AI_API_KEY` - 您的 API 密钥
18
-
19
- 对于 `Z_AI_MODE=ZHIPU`:使用智谱 AI 平台 https://bigmodel.cn
20
-
21
- 对于 `Z_AI_MODE=ZAI`:使用 ZAI 平台 https://z.ai/model-api
22
-
23
-
24
- ## 安装
25
-
26
- ### 从 npm 安装
27
-
28
- ```bash
29
- npm i @z_ai/mcp-server
30
- ```
31
-
32
- ## 使用方法
33
-
34
- ### 在 Claude Code 中使用此 MCP 服务器
35
-
36
- ```shell
37
- claude mcp add zai-mcp-server --env Z_AI_API_KEY=your_api_key -- npx -y "@z_ai/mcp-server"
38
- ```
39
-
40
- ### 在其他客户端中使用此 MCP 服务器
41
-
42
- 参考文档 [视觉理解 MCP](https://docs.bigmodel.cn/cn/coding-plan/mcp/vision-mcp-server)
@@ -1,122 +0,0 @@
1
- /**
2
- * Create multimodal message content
3
- * @param content Content array including images, text, etc.
4
- * @param prompt Text prompt
5
- * @returns Formatted message array
6
- */
7
- export function createMultiModalMessage(content, prompt) {
8
- return [{
9
- role: 'user',
10
- content: [...content, { type: 'text', text: prompt }]
11
- }];
12
- }
13
- /**
14
- * Create text message
15
- * @param prompt Text content
16
- * @returns Formatted message array
17
- */
18
- export function createTextMessage(prompt) {
19
- return [{
20
- role: 'user',
21
- content: [{ type: 'text', text: prompt }]
22
- }];
23
- }
24
- /**
25
- * Create image message content
26
- * @param imageUrl Image URL or base64 data
27
- * @returns Image content object
28
- */
29
- export function createImageContent(imageUrl) {
30
- return {
31
- type: 'image_url',
32
- image_url: { url: imageUrl }
33
- };
34
- }
35
- /**
36
- * Create video message content
37
- * @param videoUrl Video URL or base64 data
38
- * @returns Video content object
39
- */
40
- export function createVideoContent(videoUrl) {
41
- return {
42
- type: 'video_url', // Most AI models treat video as image_url type
43
- video_url: { url: videoUrl }
44
- };
45
- }
46
- /**
47
- * Create error response
48
- * @param message Error message
49
- * @param error Optional error object
50
- * @returns Standardized error response
51
- */
52
- export function createErrorResponse(message, error) {
53
- return {
54
- success: false,
55
- error: message,
56
- timestamp: Date.now(),
57
- ...(error && { context: { stack: error.stack, name: error.name } })
58
- };
59
- }
60
- /**
61
- * Create success response
62
- * @param data Response data
63
- * @returns Standardized success response
64
- */
65
- export function createSuccessResponse(data) {
66
- return {
67
- success: true,
68
- data,
69
- timestamp: Date.now()
70
- };
71
- }
72
- /**
73
- * Format response content to MCP format
74
- * @param response API response
75
- * @returns MCP tool response format
76
- */
77
- export function formatMcpResponse(response) {
78
- if (response.success) {
79
- const text = typeof response.data === 'string'
80
- ? response.data
81
- : JSON.stringify(response.data, null, 2);
82
- return {
83
- content: [{ type: 'text', text }]
84
- };
85
- }
86
- else {
87
- return {
88
- content: [{
89
- type: 'text',
90
- text: `Error: ${response.error}`
91
- }],
92
- isError: true
93
- };
94
- }
95
- }
96
- /**
97
- * Create async function with retry mechanism
98
- * @param fn Async function to execute
99
- * @param maxRetries Maximum retry attempts
100
- * @param delay Retry delay in milliseconds
101
- * @returns Wrapped function
102
- */
103
- export function withRetry(fn, maxRetries = 3, delay = 1000) {
104
- return async (...args) => {
105
- let lastError;
106
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
107
- try {
108
- return await fn(...args);
109
- }
110
- catch (error) {
111
- lastError = error instanceof Error ? error : new Error(String(error));
112
- if (attempt === maxRetries) {
113
- throw lastError;
114
- }
115
- // Exponential backoff
116
- const waitTime = delay * Math.pow(2, attempt);
117
- await new Promise(resolve => setTimeout(resolve, waitTime));
118
- }
119
- }
120
- throw lastError;
121
- };
122
- }
@@ -1,80 +0,0 @@
1
- import { ApiError } from '../types/index.js';
2
- import { configurationService } from './environment.js';
3
- import { EnvironmentService } from './environment.js';
4
- /**
5
- * ZAI API service implementation
6
- */
7
- export class ChatService {
8
- environmentService;
9
- constructor(environmentService = EnvironmentService.getInstance()) {
10
- this.environmentService = environmentService;
11
- }
12
- /**
13
- * ZAI chat completions API for vision analysis
14
- */
15
- async visionCompletions(messages) {
16
- const visionConfig = configurationService.getVisionConfig();
17
- const requestBody = {
18
- model: visionConfig.model,
19
- messages,
20
- thinking: { type: 'enabled' },
21
- stream: false,
22
- temperature: visionConfig.temperature,
23
- top_p: visionConfig.topP,
24
- max_tokens: visionConfig.maxTokens
25
- };
26
- console.info('Request ZAI chat completions API for vision analysis', { model: visionConfig.model, messageCount: messages.length });
27
- try {
28
- const response = await this.chatCompletions(visionConfig.url, requestBody);
29
- const result = response.choices?.[0]?.message?.content;
30
- if (!result) {
31
- throw new ApiError('Invalid API response: missing content');
32
- }
33
- console.info('Request chat completions API for vision analysis successful');
34
- return result;
35
- }
36
- catch (error) {
37
- console.error('Request chat completions API for vision analysis failed', { error: error instanceof Error ? error.message : String(error) });
38
- throw error instanceof ApiError ? error : new ApiError(`API call failed: ${error}`);
39
- }
40
- }
41
- /**
42
- * Make HTTP request to ZAI API with proper headers and error handling
43
- */
44
- async chatCompletions(url, body) {
45
- const apiConfig = configurationService.getVisionConfig();
46
- const apiKey = this.environmentService.getApiKey();
47
- const controller = new AbortController();
48
- const timeoutId = setTimeout(() => controller.abort(), apiConfig.timeout);
49
- try {
50
- const response = await fetch(url, {
51
- method: 'POST',
52
- headers: {
53
- 'Authorization': `Bearer ${apiKey}`,
54
- 'Content-Type': 'application/json',
55
- 'X-Title': '4.5V MCP Local',
56
- 'Accept-Language': 'en-US,en'
57
- },
58
- body: JSON.stringify(body),
59
- signal: controller.signal
60
- });
61
- clearTimeout(timeoutId);
62
- if (!response.ok) {
63
- const errorText = await response.text();
64
- throw new ApiError(`HTTP ${response.status}: ${errorText}`);
65
- }
66
- return await response.json();
67
- }
68
- catch (error) {
69
- clearTimeout(timeoutId);
70
- if (error instanceof ApiError) {
71
- throw error;
72
- }
73
- throw new ApiError(`Network error: ${error}`);
74
- }
75
- }
76
- }
77
- /**
78
- * ZAI API chat completions service instance
79
- */
80
- export const chatService = new ChatService();
@@ -1,128 +0,0 @@
1
- import { ApiError } from '../types/index.js';
2
- /**
3
- * Environment configuration service using singleton pattern
4
- */
5
- export class EnvironmentService {
6
- static instance;
7
- config = null;
8
- constructor() { }
9
- /**
10
- * Get singleton instance of EnvironmentService
11
- */
12
- static getInstance() {
13
- if (!EnvironmentService.instance) {
14
- EnvironmentService.instance = new EnvironmentService();
15
- }
16
- return EnvironmentService.instance;
17
- }
18
- /**
19
- * Get environment configuration
20
- */
21
- getConfig() {
22
- if (!this.config) {
23
- this.config = this.loadEnvironmentConfig();
24
- }
25
- return this.config;
26
- }
27
- /**
28
- * Load environment configuration from process.env
29
- */
30
- loadEnvironmentConfig() {
31
- const envConfig = { ...process.env };
32
- if (!envConfig.Z_AI_BASE_URL) {
33
- // for z.ai paas is https://api.z.ai/api/paas/v4/
34
- // for zhipuai is https://open.bigmodel.cn/api/paas/v4/
35
- envConfig.Z_AI_BASE_URL = 'https://open.bigmodel.cn/api/paas/v4/';
36
- }
37
- if (envConfig.PLATFORM_MODE != null) {
38
- console.info('Running in mode', { mode: envConfig.PLATFORM_MODE });
39
- if (envConfig.PLATFORM_MODE === 'Z_AI' || envConfig.PLATFORM_MODE === 'ZAI' || envConfig.PLATFORM_MODE === 'Z') {
40
- envConfig.Z_AI_BASE_URL = 'https://api.z.ai/api/paas/v4/';
41
- envConfig.PLATFORM_MODE = 'ZAI';
42
- }
43
- else if (envConfig.PLATFORM_MODE === 'ZHIPU_AI' || envConfig.PLATFORM_MODE === 'ZHIPUAI'
44
- || envConfig.PLATFORM_MODE === 'ZHIPU' || envConfig.PLATFORM_MODE === 'BIGMODEL') {
45
- envConfig.Z_AI_BASE_URL = 'https://open.bigmodel.cn/api/paas/v4/';
46
- envConfig.PLATFORM_MODE = 'ZHIPU';
47
- }
48
- }
49
- else {
50
- envConfig.PLATFORM_MODE = 'ZHIPU';
51
- }
52
- if (!envConfig.Z_AI_API_KEY && envConfig.ZAI_API_KEY) {
53
- envConfig.Z_AI_API_KEY = envConfig.ZAI_API_KEY;
54
- console.warn("[important] Z_AI_API_KEY is not set but found ZAI_API_KEY, using ZAI_API_KEY as Z_AI_API_KEY");
55
- }
56
- // for some user forget replace the `your_api_key` `your_zhipu_api_key` `your_zai_api_key` in the env
57
- if (!envConfig.Z_AI_API_KEY || envConfig.Z_AI_API_KEY?.toLowerCase().includes('api')
58
- || envConfig.Z_AI_API_KEY?.toLowerCase().includes('key')) {
59
- if (envConfig.ANTHROPIC_AUTH_TOKEN && !envConfig.ANTHROPIC_AUTH_TOKEN?.toLowerCase().includes('api')) {
60
- // use the ANTHROPIC_AUTH_TOKEN as Z_AI_API_KEY if available
61
- envConfig.Z_AI_API_KEY = envConfig.ANTHROPIC_AUTH_TOKEN;
62
- console.warn('[important] Z_AI_API_KEY is not set but found ANTHROPIC_AUTH_TOKEN, using ANTHROPIC_AUTH_TOKEN as Z_AI_API_KEY');
63
- }
64
- else {
65
- throw new ApiError('Z_AI_API_KEY environment variable is required, please set your actual API key');
66
- }
67
- }
68
- return {
69
- Z_AI_BASE_URL: envConfig.Z_AI_BASE_URL,
70
- Z_AI_API_KEY: envConfig.Z_AI_API_KEY,
71
- Z_AI_VISION_MODEL: envConfig.Z_AI_VISION_MODEL,
72
- Z_AI_VISION_MODEL_TEMPERATURE: envConfig.Z_AI_VISION_MODEL_TEMPERATURE,
73
- Z_AI_VISION_MODEL_TOP_P: envConfig.Z_AI_VISION_MODEL_TOP_P,
74
- Z_AI_VISION_MODEL_MAX_TOKENS: envConfig.Z_AI_VISION_MODEL_MAX_TOKENS,
75
- Z_AI_TIMEOUT: envConfig.Z_AI_TIMEOUT,
76
- Z_AI_RETRY_COUNT: envConfig.Z_AI_RETRY_COUNT,
77
- SERVER_NAME: envConfig.SERVER_NAME,
78
- SERVER_VERSION: envConfig.SERVER_VERSION,
79
- PLATFORM_MODE: envConfig.PLATFORM_MODE
80
- };
81
- }
82
- /**
83
- * Get server configuration
84
- */
85
- getServerConfig() {
86
- const config = this.getConfig();
87
- return {
88
- name: config.SERVER_NAME || 'zai-mcp-server',
89
- version: config.SERVER_VERSION || '0.1.0'
90
- };
91
- }
92
- /**
93
- * Get platform mode
94
- */
95
- getPlatformModel() {
96
- const config = this.getConfig();
97
- return config.PLATFORM_MODE || 'ZHIPU';
98
- }
99
- /**
100
- * Get API configuration
101
- */
102
- getVisionConfig() {
103
- const config = this.getConfig();
104
- return {
105
- model: config.Z_AI_VISION_MODEL || 'glm-4.5v',
106
- timeout: parseInt(config.Z_AI_TIMEOUT || '300000'),
107
- retryCount: parseInt(config.Z_AI_RETRY_COUNT || '1'),
108
- url: config.Z_AI_BASE_URL + 'chat/completions',
109
- temperature: parseFloat(config.Z_AI_VISION_MODEL_TEMPERATURE || '0.8'),
110
- topP: parseFloat(config.Z_AI_VISION_MODEL_TOP_P || '0.6'),
111
- maxTokens: parseInt(config.Z_AI_VISION_MODEL_MAX_TOKENS || '16384')
112
- };
113
- }
114
- /**
115
- * Get ZAI API key from configuration
116
- */
117
- getApiKey() {
118
- return this.getConfig().Z_AI_API_KEY;
119
- }
120
- }
121
- /**
122
- * Global environment service instance
123
- */
124
- export const environmentService = EnvironmentService.getInstance();
125
- /**
126
- * Configuration service instance (for backward compatibility)
127
- */
128
- export const configurationService = environmentService;