feat(mcp): add code import functionality for MCP service configuration

Implement a new feature that allows users to import MCP service configurations via a standard JSON format. This includes:

- A toggle for importing from code with a user-friendly hint and placeholder.
- Error handling for various scenarios such as empty input, invalid JSON, and missing URLs.
- Toast notifications for successful imports and warnings about ignored headers.
- Updates to the MCP service dialog to support this new functionality, ensuring a seamless user experience during service creation and editing.
This commit is contained in:
wizardchen
2026-06-22 20:43:57 +08:00
committed by lyingbug
parent 3eb49da746
commit 518add2641
6 changed files with 312 additions and 4 deletions
+20
View File
@@ -4387,6 +4387,26 @@ export default {
updated: 'MCP service updated',
createFailed: 'Failed to create MCP service',
updateFailed: 'Failed to update MCP service'
},
codeImport: {
toggle: 'Import from code',
hint: 'Paste a standard mcpServers JSON config to auto-fill the form',
placeholder:
'{\n "mcpServers": {\n "my-server": {\n "url": "https://example.com/sse"\n }\n }\n}',
parse: 'Parse & Fill',
editOverwriteHint: 'Importing overwrites the current form (saved credentials are unaffected; click Save to apply)',
errors: {
empty: 'Please paste the config first',
invalidJson: 'Unable to parse, please check the JSON format',
noServer: 'No MCP service config found',
missingUrl: 'The config is missing a url',
stdioUnsupported: 'stdio (command/args) configs are not supported; please use a remote config with a url'
},
toasts: {
filled: 'Form filled, please review and save',
multipleServers: 'Multiple services detected, imported the first one: {name}',
ignoredHeaders: 'The following headers were not imported: {headers}'
}
}
},
promptTemplate: {
+20
View File
@@ -4384,6 +4384,26 @@ export default {
createFailed: "MCP 서비스 생성 실패",
updateFailed: "MCP 서비스 업데이트 실패",
},
codeImport: {
toggle: "코드에서 가져오기",
hint: "표준 mcpServers JSON 설정을 붙여넣으면 양식이 자동으로 채워집니다",
placeholder:
'{\n "mcpServers": {\n "my-server": {\n "url": "https://example.com/sse"\n }\n }\n}',
parse: "파싱 후 채우기",
editOverwriteHint: "가져오기는 현재 양식을 덮어씁니다(저장된 자격 증명은 영향받지 않으며, 저장을 눌러야 적용됩니다)",
errors: {
empty: "먼저 설정을 붙여넣어 주세요",
invalidJson: "파싱할 수 없습니다. JSON 형식을 확인해 주세요",
noServer: "MCP 서비스 설정을 찾을 수 없습니다",
missingUrl: "설정에 url이 없습니다",
stdioUnsupported: "stdio(command/args) 설정은 지원되지 않습니다. url이 포함된 원격 설정을 사용해 주세요",
},
toasts: {
filled: "양식이 채워졌습니다. 확인 후 저장해 주세요",
multipleServers: "여러 서비스가 감지되어 첫 번째 항목을 가져왔습니다: {name}",
ignoredHeaders: "다음 헤더는 가져오지 않았습니다: {headers}",
},
},
},
promptTemplate: {
noTemplates: "아직 템플릿이 없습니다.",
+20
View File
@@ -4036,6 +4036,26 @@ export default {
updated: 'Сервис MCP обновлён',
createFailed: 'Не удалось создать сервис MCP',
updateFailed: 'Не удалось обновить сервис MCP'
},
codeImport: {
toggle: 'Импорт из кода',
hint: 'Вставьте стандартную JSON-конфигурацию mcpServers для автозаполнения формы',
placeholder:
'{\n "mcpServers": {\n "my-server": {\n "url": "https://example.com/sse"\n }\n }\n}',
parse: 'Разобрать и заполнить',
editOverwriteHint: 'Импорт перезапишет текущую форму (сохранённые учётные данные не затрагиваются; нажмите «Сохранить», чтобы применить)',
errors: {
empty: 'Сначала вставьте конфигурацию',
invalidJson: 'Не удалось разобрать, проверьте формат JSON',
noServer: 'Конфигурация сервиса MCP не найдена',
missingUrl: 'В конфигурации отсутствует url',
stdioUnsupported: 'Конфигурации stdio (command/args) не поддерживаются; используйте удалённую конфигурацию с url'
},
toasts: {
filled: 'Форма заполнена, проверьте и сохраните',
multipleServers: 'Обнаружено несколько сервисов, импортирован первый: {name}',
ignoredHeaders: 'Следующие заголовки не импортированы: {headers}'
}
}
},
manualEditor: {
+20
View File
@@ -4406,6 +4406,26 @@ export default {
revoked: "已撤销授权",
revokeFailed: "撤销失败",
},
codeImport: {
toggle: "从代码导入",
hint: "粘贴标准 mcpServers JSON 配置,自动填充表单",
placeholder:
'{\n "mcpServers": {\n "my-server": {\n "url": "https://example.com/sse"\n }\n }\n}',
parse: "解析并填充",
editOverwriteHint: "导入会覆盖当前表单内容(不影响已保存的凭证,需点保存生效)",
errors: {
empty: "请先粘贴配置内容",
invalidJson: "无法解析,请检查 JSON 格式",
noServer: "未找到 MCP 服务配置",
missingUrl: "配置缺少 url",
stdioUnsupported: "暂不支持 stdio(command/args)配置,请使用带 url 的远程配置",
},
toasts: {
filled: "已填充表单,请检查后保存",
multipleServers: "检测到多个服务,已导入第一个:{name}",
ignoredHeaders: "以下 header 未导入:{headers}",
},
},
},
promptTemplate: {
noTemplates: "暂无模板",
+14 -1
View File
@@ -112,6 +112,7 @@
:service="currentService"
:mode="dialogMode"
@success="handleDialogSuccess"
@created="handleDialogCreated"
/>
</div>
</template>
@@ -182,12 +183,24 @@ const handleEdit = (service: MCPService) => {
dialogVisible.value = true
}
// Handle dialog success
// Handle dialog success (edit-mode update): close + refresh.
const handleDialogSuccess = () => {
dialogVisible.value = false
loadServices()
}
// Handle first create: keep the drawer open and flip it to edit mode bound to
// the newly created service, so OAuth authorization and "test connection"
// (both of which need a saved service id) are usable right away. The list is
// refreshed in the background; we prefer the freshly-fetched record so the
// edit form sees server-side fields (e.g. credential metadata).
const handleDialogCreated = async (created: MCPService) => {
await loadServices()
const full = services.value.find((s) => s.id === created.id) || created
currentService.value = { ...full }
dialogMode.value = 'edit'
}
// Handle toggle enabled/disabled
const handleToggleEnabled = async (service: MCPService) => {
if (!service || !service.id) return
@@ -59,6 +59,35 @@
</template>
<t-form ref="formRef" :data="formData" :rules="rules" label-align="top">
<!--
从代码导入:粘贴标准 mcpServers JSON,纯前端解析后填回表单。
不自动提交;用户检查后再点保存。
-->
<section class="setting-drawer__section code-import">
<button type="button" class="code-import__toggle" @click="codeImportOpen = !codeImportOpen">
<t-icon :name="codeImportOpen ? 'chevron-down' : 'chevron-right'" />
<span>{{ t('mcpServiceDialog.codeImport.toggle') }}</span>
</button>
<div v-if="codeImportOpen" class="code-import__body">
<p class="form-desc">{{ t('mcpServiceDialog.codeImport.hint') }}</p>
<p v-if="mode === 'edit'" class="form-desc code-import__warn">
{{ t('mcpServiceDialog.codeImport.editOverwriteHint') }}
</p>
<t-textarea
v-model="codeImportText"
:autosize="{ minRows: 5, maxRows: 14 }"
:placeholder="t('mcpServiceDialog.codeImport.placeholder')"
class="code-import__textarea"
/>
<p v-if="codeImportError" class="code-import__error">{{ codeImportError }}</p>
<div class="code-import__actions">
<t-button theme="primary" variant="outline" @click="handleCodeImport">
{{ t('mcpServiceDialog.codeImport.parse') }}
</t-button>
</div>
</div>
</section>
<!-- Section 1 — 基本信息 -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.basicSection', '基本信息') }}</h4>
@@ -319,6 +348,9 @@ interface Props {
interface Emits {
(e: 'update:visible', value: boolean): void
(e: 'success'): void
// Emitted after a successful create; carries the newly created service so
// the parent can transition the drawer to edit mode without closing it.
(e: 'created', service: MCPService): void
}
const props = defineProps<Props>()
@@ -351,6 +383,134 @@ const formData = ref({
},
})
// ---- Code import (paste standard mcpServers JSON) ----
const codeImportOpen = ref(false)
const codeImportText = ref('')
const codeImportError = ref('')
// Map a raw MCP server config object onto the form. Stdio is rejected.
function applyServerConfig(name: string, cfg: Record<string, unknown>) {
if (cfg.command) {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.stdioUnsupported')
return false
}
const url = typeof cfg.url === 'string' ? cfg.url.trim() : ''
if (!url) {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.missingUrl')
return false
}
// Transport: explicit type/transport wins, else guess from the URL shape.
const rawType = String(cfg.type ?? cfg.transport ?? '').toLowerCase()
let transport: 'sse' | 'http-streamable'
if (rawType === 'sse') {
transport = 'sse'
} else if (['http', 'http-streamable', 'streamable-http', 'streamablehttp', 'streamable_http'].includes(rawType)) {
transport = 'http-streamable'
} else {
transport = /\/sse\/?($|\?)/i.test(url) ? 'sse' : 'http-streamable'
}
// Auth: recognise Bearer / API-key headers; other headers can't be held by
// the form, so collect them to warn the user about what was dropped.
let authType: '' | 'api_key' | 'bearer' = ''
let token = ''
let apiKey = ''
const ignoredHeaders: string[] = []
const headers = (cfg.headers && typeof cfg.headers === 'object')
? (cfg.headers as Record<string, unknown>)
: {}
for (const [key, val] of Object.entries(headers)) {
const lowerKey = key.toLowerCase()
const strVal = typeof val === 'string' ? val : String(val ?? '')
if (lowerKey === 'authorization' && /^bearer\s+/i.test(strVal)) {
authType = 'bearer'
token = strVal.replace(/^bearer\s+/i, '').trim()
} else if (['x-api-key', 'api-key', 'apikey'].includes(lowerKey)) {
authType = 'api_key'
apiKey = strVal.trim()
} else {
ignoredHeaders.push(key)
}
}
formData.value.name = name || formData.value.name
formData.value.url = url
formData.value.transport_type = transport
if (typeof cfg.description === 'string') formData.value.description = cfg.description
formData.value.auth_config.auth_type = authType
formData.value.auth_config.token = token
formData.value.auth_config.api_key = apiKey
formData.value.auth_config.scopes = []
if (ignoredHeaders.length) {
MessagePlugin.warning(
t('mcpServiceDialog.codeImport.toasts.ignoredHeaders', { headers: ignoredHeaders.join(', ') }) as string,
)
}
return true
}
const handleCodeImport = () => {
codeImportError.value = ''
const raw = codeImportText.value.trim()
if (!raw) {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.empty')
return
}
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.invalidJson')
return
}
if (!parsed || typeof parsed !== 'object') {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.noServer')
return
}
const obj = parsed as Record<string, unknown>
let name = ''
let cfg: Record<string, unknown> | null = null
let multiple = false
const servers = obj.mcpServers
if (servers && typeof servers === 'object') {
const entries = Object.entries(servers as Record<string, unknown>)
if (entries.length === 0) {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.noServer')
return
}
multiple = entries.length > 1
name = entries[0][0]
cfg = entries[0][1] as Record<string, unknown>
} else if (obj.url || obj.command) {
// Bare single-server object (no mcpServers wrapper).
cfg = obj
} else {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.noServer')
return
}
if (!cfg || typeof cfg !== 'object') {
codeImportError.value = t('mcpServiceDialog.codeImport.errors.noServer')
return
}
if (!applyServerConfig(name, cfg)) return
formRef.value?.clearValidate()
if (multiple) {
MessagePlugin.info(
t('mcpServiceDialog.codeImport.toasts.multipleServers', { name }) as string,
)
} else {
MessagePlugin.success(t('mcpServiceDialog.codeImport.toasts.filled') as string)
}
}
// Comma/space separated text binding for OAuth scopes.
const oauthScopesText = computed({
get: () => (formData.value.auth_config.scopes || []).join(' '),
@@ -630,6 +790,10 @@ watch(
// 切到不同服务(或新增)时清空上次测试反馈,避免旧的 ✓/✗ 漂在新表单上
lastTestOk.value = null
testResult.value = null
// 同时重置代码导入区域,避免上一个服务残留的粘贴内容/报错漂到新表单
codeImportOpen.value = false
codeImportText.value = ''
codeImportError.value = ''
if (service) {
const transportType = service.transport_type === 'stdio' ? 'sse' : (service.transport_type || 'sse')
formData.value = {
@@ -699,17 +863,21 @@ const handleSubmit = async () => {
if (formData.value.auth_config.token) auth.token = formData.value.auth_config.token
}
data.auth_config = auth
await createMCPService(data)
const created = await createMCPService(data)
MessagePlugin.success(t('mcpServiceDialog.toasts.created'))
// Keep the drawer open and hand back the new service so the parent can
// flip it into edit mode in place — OAuth authorization and "test
// connection" both need a saved service id, so transitioning here lets
// the user do them immediately instead of save → reopen.
emit('created', created)
} else {
// Edit-mode: never send credential fields here. CredentialResource
// already committed any changes through the dedicated endpoint.
data.auth_config = auth
await updateMCPService(props.service!.id, data)
MessagePlugin.success(t('mcpServiceDialog.toasts.updated'))
emit('success')
}
emit('success')
} catch (error) {
MessagePlugin.error(
props.mode === 'add'
@@ -733,6 +901,53 @@ const handleClose = () => {
margin-bottom: 0;
}
// ---- 从代码导入 ----
.code-import {
&__toggle {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 0;
border: none;
background: none;
cursor: pointer;
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary);
&:hover {
color: var(--td-brand-color);
}
}
&__body {
margin-top: 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
&__warn {
color: var(--td-warning-color);
}
&__textarea :deep(textarea) {
font-family: var(--td-font-family-mono, monospace);
font-size: 12px;
}
&__error {
margin: 0;
font-size: 12px;
color: var(--td-error-color);
}
&__actions {
display: flex;
justify-content: flex-end;
}
}
.oauth-status {
display: flex;
align-items: center;