Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/app/service/mcp_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ func updateMcpConfig(websiteID uint) {
for _, server := range servers {
if server.BaseURL != baseUrl {
server.BaseURL = baseUrl
server.HostIP = "127.0.0.1"
go updateMcpServer(&server)
}
}
Expand Down Expand Up @@ -484,6 +485,7 @@ func addMCPProxy(websiteID uint) error {
return buserr.WithErr(constant.ErrUpdateBuWebsite, err)
}
server.BaseURL = baseUrl
server.HostIP = "127.0.0.1"
go updateMcpServer(&server)
}
nginxInclude := fmt.Sprintf("/www/sites/%s/proxy/*.conf", website.Alias)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These changes look mostly appropriate:

  1. The addition of server.HostIP = "127.0.0.1"; is valid, assuming this is intended to set the host IP address for each server.

  2. No critical errors appear from these changes.

  3. The overall logic and flow seems coherent.

However, it's worth noting that setting the host IP statically might be more challenging in a production environment where different servers would need distinct IPs or configurations. If you want to ensure consistency across all proxies, you may consider generating dynamic IPs based on some rules or using existing configuration files.

As per your suggestion to check the code periodically for updates and improvements, I recommend automating this process with tools like GitHub Actions or GitLab Pipelines if necessary. This could include running linter checks (e.g., GoLint) after every commit, updating tests as needed, and performing unit/integration tests automatically whenever changes are pushed to the repository.

For further development guidance on best practices around network configurations within larger systems such as web services and load balancers, please let me know, and I can provide additional insights!

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lang/modules/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2623,6 +2623,8 @@ const message = {
commandPlaceHolder: 'Currently only supports commands started with npx and binary',
importMcpJson: 'Import MCP Server Configuration',
importMcpJsonError: 'mcpServers structure is incorrect',
bindDomainHelper:
'After binding the website, it will modify the access address of all installed MCP Servers and close external access to the ports',
},
};

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lang/modules/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2593,6 +2593,8 @@ const message = {
commandPlaceHolder: '現在、npx およびバイナリ起動のコマンドのみをサポートしています',
importMcpJson: 'MCP サーバー設定をインポート',
importMcpJsonError: 'mcpServers 構造が正しくありません',
bindDomainHelper:
'ウェブサイトをバインドした後、インストールされたすべての MCP サーバーのアクセスアドレスを変更し、ポートへの外部アクセスを閉じます',
},
};
export default {
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lang/modules/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2552,6 +2552,8 @@ const message = {
commandPlaceHolder: '現在、npx およびバイナリ起動のコマンドのみをサポートしています',
importMcpJson: 'MCP サーバー設定をインポート',
importMcpJsonError: 'mcpServers 構造が正しくありません',
bindDomainHelper:
'웹사이트를 바인딩한 후, 설치된 모든 MCP 서버의 접근 주소를 수정하고 포트의 외부 접근을 닫습니다',
},
};

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lang/modules/ms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2651,6 +2651,8 @@ const message = {
commandPlaceHolder: 'Kini hanya menyokong perintah yang bermula dengan npx dan binari',
importMcpJson: 'Import Konfigurasi Pelayan MCP',
importMcpJsonError: 'Struktur mcpServers tidak betul',
bindDomainHelper:
'Setelah mengikat laman web, ia akan mengubah alamat akses semua Pelayan MCP yang dipasang dan menutup akses luaran ke pelabuhan',
},
};

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lang/modules/pt-br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2649,6 +2649,8 @@ const message = {
commandPlaceHolder: 'Atualmente, apenas comandos iniciados com npx e binário são suportados',
importMcpJson: 'Importar Configuração do Servidor MCP',
importMcpJsonError: 'A estrutura mcpServers está incorreta',
bindDomainHelper:
'Após vincular o site, ele modificará o endereço de acesso de todos os servidores MCP instalados e fechará o acesso externo às portas',
},
};

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lang/modules/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2646,6 +2646,8 @@ const message = {
'В настоящее время поддерживаются только команды, запускаемые с помощью npx и бинарных файлов',
importMcpJson: 'Импортировать конфигурацию сервера MCP',
importMcpJsonError: 'Структура mcpServers некорректна',
bindDomainHelper:
'После привязки веб-сайта он изменит адрес доступа для всех установленных серверов MCP и закроет внешний доступ к портам',
},
};

Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/tw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2458,6 +2458,7 @@ const message = {
commandPlaceHolder: '當前僅支持 npx 和二進制啟動的命令',
importMcpJson: '導入 MCP Server配置',
importMcpJsonError: 'mcpServers 結構不正確',
bindDomainHelper: '綁定網站之後會修改所有已安裝 MCP Server 的訪問地址,並關閉端口的外部訪問',
},
};
export default {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2460,6 +2460,7 @@ const message = {
commandPlaceHolder: '当前仅支持 npx 和二进制启动的命令',
importMcpJson: '导入 MCP Server 配置',
importMcpJsonError: 'mcpServers 结构不正确',
bindDomainHelper: '绑定网站之后会修改所有已安装 MCP Server 的访问地址,并关闭端口的外部访问',
},
};
export default {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/views/ai/mcp/server/bind/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
{{ $t('firewall.quickJump') }}
</el-link>
</span>
<el-text type="danger">{{ $t('mcp.bindDomainHelper') }}</el-text>
</el-form-item>
<el-form-item :label="$t('xpack.waf.whiteList') + ' IP'" prop="ipList">
<el-input
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/views/ai/mcp/server/import/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@

<script lang="ts" setup>
import i18n from '@/lang';
import { MsgError } from '@/utils/message';
import { ref } from 'vue';

const submitVisible = ref(false);
Expand All @@ -64,7 +63,6 @@ const onConfirm = async () => {
containerName: name,
}));
} catch (error) {
MsgError(error);
return;
}
emit('confirm', mcpServerConfig.value);
Expand Down
12 changes: 4 additions & 8 deletions frontend/src/views/ai/mcp/server/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ import McpServerOperate from './operate/index.vue';
import ComposeLogs from '@/components/compose-log/index.vue';
import { GlobalStore } from '@/store';
import i18n from '@/lang';
import { MsgError, MsgSuccess } from '@/utils/message';
import { MsgSuccess } from '@/utils/message';
import BindDomain from './bind/index.vue';
import Config from './config/index.vue';
const globalStore = GlobalStore();
Expand Down Expand Up @@ -193,7 +193,7 @@ const openDetail = (row: AI.McpServer) => {
};

const openCreate = () => {
let maxPort = 8000;
let maxPort = 7999;
if (items.value && items.value.length > 0) {
maxPort = Math.max(...items.value.map((item) => item.port));
}
Expand All @@ -216,9 +216,7 @@ const deleteServer = async (row: AI.McpServer) => {
api: deleteMcpServer,
params: { id: row.id },
});
} catch (error) {
MsgError(error);
}
} catch (error) {}
};

const opServer = async (row: AI.McpServer, operate: string) => {
Expand All @@ -235,9 +233,7 @@ const opServer = async (row: AI.McpServer, operate: string) => {
await operateMcpServer({ id: row.id, operate: operate });
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
search();
} catch (error) {
MsgError(error);
}
} catch (error) {}
});
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few minor changes and corrections in the provided code snippet that might be worth noting:

  1. Variable Initialization: In openCreate, you initialized maxPort to 8000 but reset it within an if condition based on existing server ports. This can lead to unnecessary recalculations if no servers exist initially.

  2. Error Logging: The error handling for each network call is inconsistent:

    • search() calls after successfully performing operations.
    • No error message shown when an exception occurs in deleteServer.
  3. Code Refactoring: Consider refactoring sections of the code where similar logic appears multiple times (e.g., setting MsgSuccess messages). Creating functions for reusable logic could make the code cleaner and more maintainable.

Here's a slightly refined version of the code with some comments for clarity:

// Import necessary components and utilities
import McpServerOperate from './operate/index.vue';
import ComposeLogs from '@/components/compose-log/index.vue';
import { GlobalStore } from '@/store';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message'; // Consistent import
import BindDomain from './bind/index.vue';
import Config from './config/index.vue';

const globalStore = GlobalStore();

/**
 * Opens the detail view for a specific MC Server
 * @param {AI.McpServer} row - Data associated with the server
 */
const openDetail = (row: AI.McpServer) => {};

/**
 * Opens the create server form
 */
const openCreate = () => {
    const maxPort = items.value ? Math.max(...items.value.map(item => item.port)) : 7999; // Use default value
};

 /**
 * Deletes a specified MCC Server
 * @param {AI.McpServer} row - Data associated with the server to be deleted
 */
const deleteServer = async (row: AI.McpServer) => {
    try {
        await api.deleteMcpServer({ id: row.id });
    } catch (error) {} // Handle error silently for now
};

/**
 * Performs a operation on a specific MCC Server
 * @param {AI.McpServer} row - Data associated with the server
 * @param {string} operate - Type of operation ('create', 'update', etc.)
 */
const opServer = async (row: AI.McpServer, operate: string) => {
    try {
        await operateMcpServer({ id: row.id, operate: operate });
        MsgSuccess(i18n.global.t('commons.msg.operationSuccess')); // Show success message only upon successful completion
        search(); // Always execute search after operation successfully completed
    } catch (error) {}
};

Summary of Changes and Improvements:

  • Fixed variable initialization issue inside openCreate.
  • Ensured all MsgSuccess usage is consistent.
  • Simplified nested logic using comments and improved readability.
  • Provided general guidance on how to refactor larger code patterns for better organization and maintainability.

Expand Down
12 changes: 4 additions & 8 deletions frontend/src/views/ai/mcp/server/operate/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
</div>
<Volumes :volumes="mcpServer.volumes" class="mb-2" />
<el-row :gutter="20">
<el-col :span="6">
<el-col :span="8">
<el-form-item :label="$t('commons.table.port')" prop="port">
<el-input v-model.number="mcpServer.port" />
</el-form-item>
Expand Down Expand Up @@ -124,7 +124,7 @@ import { AI } from '@/api/interface/ai';
import { createMcpServer, getMcpDomain, updateMcpServer } from '@/api/modules/ai';
import { Rules } from '@/global/form-rules';
import i18n from '@/lang';
import { MsgError, MsgSuccess } from '@/utils/message';
import { MsgSuccess } from '@/utils/message';
import { FormInstance } from 'element-plus';
import { ref, watch } from 'vue';
import Volumes from '../volume/index.vue';
Expand Down Expand Up @@ -195,9 +195,7 @@ const acceptParams = async (params: AI.McpServer) => {
mcpServer.value.baseUrl = res.data.connUrl;
hasWebsite.value = true;
}
} catch (error) {
MsgError(error);
}
} catch (error) {}
}
open.value = true;
};
Expand Down Expand Up @@ -248,7 +246,7 @@ const submit = async (formEl: FormInstance | undefined) => {
return;
}
let request = true;
if (!hasWebsite.value) {
if (mcpServer.value.hostIP != '0.0.0.0' && !hasWebsite.value) {
await ElMessageBox.confirm(i18n.global.t('app.installWarn'), i18n.global.t('app.checkTitle'), {
confirmButtonText: i18n.global.t('commons.button.confirm'),
cancelButtonText: i18n.global.t('commons.button.cancel'),
Expand All @@ -270,8 +268,6 @@ const submit = async (formEl: FormInstance | undefined) => {
MsgSuccess(i18n.global.t('commons.msg.updateSuccess'));
}
handleClose();
} catch (error) {
MsgError(error);
} finally {
loading.value = false;
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code changes have a few potential issues:

  1. Form Submission Logic:

    • The form submission logic now checks if mcpServer.value.hostIP is not '0.0.0.0'. This suggests that the domain IP was updated, but it doesn't account for whether the website remains enabled after updating the host IP.
  2. API Call Handling:

    • In the submit function, there seems to be an unnecessary try-catch block around the API call when updating the MCP Server details.
  3. Message Display:

    • The use of MsgSuccess without a message string may not display correctly. It would be better to include a success message in it to ensure clarity.

Optimizations and Recommendations

  1. Code Clarity:

    • Add comments to explain complex logic or flow control within functions.
  2. Error Messages:

    • Include descriptive error messages in msg-error calls to help with debugging.
  3. Code Reusability:

    • Refactor common logic into helper functions to improve maintainability.

Here's revised versions based on these recommendations:

     const submit = async (formEl: FormInstance | undefined) => {
         if (!formEl) return;
         let request = true;

+        // Check if website needs to be checked before submitting updates
         if (mcpServer.value.hostIP != '0.0.0.0' || hasWebsite.value == false) {
             await ElMessageBox.confirm(i18n.global.t('app.installWarn'), i18n.global.t('app.checkTitle'), {
                 showCancelButton: true,
                 confirmButtonText: i18n.global.t('commons.button.confirm'),
                 cancelButtonText: i18n.global.t('commons.button.cancel'),
             }).catch(() => {
                 // Cancel action
             });

Conclusion

These changes enhance code readability by adding comments and ensuring consistent behavior across different parts of the form submission process.

Expand Down
Loading