The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(mcp): resolve and declare hosted registry servers (#7194)
oxoxDevffeb11df5e3c
diff --git a/app/src/components/channels/mcp/registryAdd.test.ts b/app/src/components/channels/mcp/registryAdd.test.tsnew file mode 100644index 0000000000..e5e056bac6--- /dev/null+++ b/app/src/components/channels/mcp/registryAdd.test.ts@@ -0,0 +1,182 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { declareServer, isAddCandidate, resolveHostedEntry } from './registryAdd';+import type { SmitheryConnection, SmitheryServer, SmitheryServerDetail } from './types';++const mockConfigGet = vi.fn();+const mockConfigSet = vi.fn();++vi.mock('../../../services/api/mcpClientsApi', () => ({+ mcpClientsApi: {+ configGet: (...args: unknown[]) => mockConfigGet(...args),+ configSet: (...args: unknown[]) => mockConfigSet(...args),+ },+}));++const SERVER: SmitheryServer = {+ qualified_name: 'com.example/open',+ display_name: 'Open',+ is_deployed: true,+ source: 'mcp_official',+};++const http = (deployment_url: string, extra: Partial<SmitheryConnection> = {}) =>+ ({ type: 'http', deployment_url, ...extra }) as SmitheryConnection;++const detail = (+ connections: SmitheryConnection[],+ extra: Partial<SmitheryServerDetail> = {}+): SmitheryServerDetail => ({ ...SERVER, connections, required_env_keys: [], ...extra });++describe('isAddCandidate', () => {+ it('offers Add only for hosted, non-Smithery, non-API-key rows', () => {+ expect(isAddCandidate(SERVER)).toBe(true);+ expect(isAddCandidate({ ...SERVER, source: 'smithery' })).toBe(false);+ expect(isAddCandidate({ ...SERVER, auth_kind: 'api_key' })).toBe(false);+ expect(isAddCandidate({ ...SERVER, is_deployed: false })).toBe(false);+ expect(isAddCandidate({ ...SERVER, is_deployed: undefined })).toBe(false);+ });+});++describe('resolveHostedEntry', () => {+ it('declares the one hosted endpoint, with no headers or type', () => {+ const result = resolveHostedEntry(+ detail([http('https://mcp.example.com/mcp'), { type: 'stdio' }]),+ SERVER+ );+ expect(result).toEqual({ ok: true, entry: { url: 'https://mcp.example.com/mcp' } });+ });++ it('accepts sse connections and repeats of the same url', () => {+ const sse = { type: 'sse', deployment_url: 'https://mcp.example.com/sse' } as unknown;+ const result = resolveHostedEntry(+ detail([sse as SmitheryConnection, sse as SmitheryConnection]),+ SERVER+ );+ expect(result).toEqual({ ok: true, entry: { url: 'https://mcp.example.com/sse' } });+ });++ it('passes the description through', () => {+ expect(+ resolveHostedEntry(detail([http('https://a.example/mcp')]), {+ ...SERVER,+ description: ' Does things. ',+ })+ ).toEqual({ ok: true, entry: { url: 'https://a.example/mcp', description: 'Does things.' } });+ expect(+ resolveHostedEntry(detail([http('https://a.example/mcp')], { description: 'From detail' }), {+ ...SERVER,+ })+ ).toEqual({ ok: true, entry: { url: 'https://a.example/mcp', description: 'From detail' } });+ });++ it.each([+ ['a stdio-only server', detail([{ type: 'stdio' }]), 'no_hosted_connection'],+ ['no connections at all', { ...SERVER } as SmitheryServerDetail, 'no_hosted_connection'],+ ['a hosted connection without a url', detail([{ type: 'http' }]), 'missing_url'],+ ['a templated url', detail([http('https://{tenant}.example.com/mcp')]), 'templated_url'],+ ['an unparsable url', detail([http('not a url')]), 'invalid_url'],+ ['a non-http scheme', detail([http('ws://mcp.example.com')]), 'unsupported_scheme'],+ [+ 'more than one distinct url',+ detail([http('https://a.example/mcp'), http('https://b.example/mcp')]),+ 'multiple_urls',+ ],+ [+ 'a required schema input',+ detail([+ http('https://a.example/mcp', {+ config_schema: { properties: { region: {} }, required: ['region'] },+ }),+ ]),+ 'requires_input',+ ],+ [+ 'a secret schema property',+ detail([+ http('https://a.example/mcp', {+ config_schema: { properties: { Authorization: { 'x-secret': true } } },+ }),+ ]),+ 'secret_input',+ ],+ [+ 'an isSecret schema property',+ detail([+ http('https://a.example/mcp', {+ config_schema: { properties: { token: { isSecret: true }, note: 'x' } },+ }),+ ]),+ 'secret_input',+ ],+ [+ 'required env keys',+ detail([http('https://a.example/mcp')], { required_env_keys: ['API_KEY'] }),+ 'requires_env',+ ],+ ])('refuses %s', (_label, input, reason) => {+ expect(resolveHostedEntry(input as SmitheryServerDetail, SERVER)).toEqual({+ ok: false,+ reason,+ });+ });++ it('accepts optional, non-secret schema properties', () => {+ const result = resolveHostedEntry(+ detail([+ http('https://a.example/mcp', {+ config_schema: { properties: { logLevel: { description: 'verbosity' } } },+ }),+ ]),+ SERVER+ );+ expect(result.ok).toBe(true);+ });+});++describe('declareServer', () => {+ beforeEach(() => {+ mockConfigGet.mockReset();+ mockConfigSet.mockReset();+ });++ it('leaves an existing entry alone and writes nothing', async () => {+ mockConfigGet.mockResolvedValue({+ mcpServers: { 'com.example/open': { url: 'https://old.example' } },+ });+ await expect(declareServer('com.example/open', { url: 'https://new.example' })).resolves.toBe(+ 'exists'+ );+ expect(mockConfigSet).not.toHaveBeenCalled();+ });++ it('adds the entry and keeps every other one', async () => {+ mockConfigGet.mockResolvedValue({+ mcpServers: { echo: { command: 'npx', args: ['-y', 'echo'], envKeys: ['K'] } },+ });+ mockConfigSet.mockResolvedValue({ mcpServers: {}, added: [], updated: [], removed: [] });+ await expect(declareServer('com.example/open', { url: 'https://a.example' })).resolves.toBe(+ 'added'+ );+ expect(mockConfigSet).toHaveBeenCalledWith({+ mcpServers: {+ echo: { command: 'npx', args: ['-y', 'echo'], envKeys: ['K'] },+ 'com.example/open': { url: 'https://a.example' },+ },+ });+ });++ it('treats a missing mcpServers map as empty', async () => {+ mockConfigGet.mockResolvedValue({});+ mockConfigSet.mockResolvedValue({ mcpServers: {}, added: [], updated: [], removed: [] });+ await expect(declareServer('x', { url: 'https://a.example' })).resolves.toBe('added');+ expect(mockConfigSet).toHaveBeenCalledWith({ mcpServers: { x: { url: 'https://a.example' } } });+ });++ it('rethrows a core refusal verbatim', async () => {+ mockConfigGet.mockResolvedValue({ mcpServers: {} });+ const refusal = new Error('`x` needs a `url` (hosted) or a `command` (run locally)');+ mockConfigSet.mockRejectedValue(refusal);+ await expect(declareServer('x', { url: 'https://a.example' })).rejects.toBe(refusal);+ });+});diff --git a/app/src/components/channels/mcp/registryAdd.ts b/app/src/components/channels/mcp/registryAdd.tsnew file mode 100644index 0000000000..8a3b9b48de--- /dev/null+++ b/app/src/components/channels/mcp/registryAdd.ts@@ -0,0 +1,119 @@+/**+ * Adding a hosted directory server to `mcp.json` in one step.+ *+ * Only a server that can be dialled as declared qualifies: one hosted+ * endpoint with a concrete http(s) URL and nothing for the user to fill in.+ * Anything else keeps the "open its page" path, where the user reads the+ * install instructions and declares it by hand.+ */+import debug from 'debug';++import { mcpClientsApi } from '../../../services/api/mcpClientsApi';+import type { SmitheryServer, SmitheryServerDetail } from './types';++const log = debug('mcp-clients:registry-add');++const HOSTED_TYPES = new Set(['http', 'sse']);+const TEMPLATE_VAR = /\{[^}]*\}/;++export type HostedEntry = { url: string; description?: string };++export type ResolveRefusal =+ | 'no_hosted_connection'+ | 'missing_url'+ | 'templated_url'+ | 'invalid_url'+ | 'unsupported_scheme'+ | 'multiple_urls'+ | 'requires_input'+ | 'secret_input'+ | 'requires_env';++export type ResolveResult =+ | { ok: true; entry: HostedEntry }+ | { ok: false; reason: ResolveRefusal };++export type DeclareOutcome = 'added' | 'exists';++/** Whether a directory row is worth offering the one-step Add for. */+export const isAddCandidate = (server: SmitheryServer): boolean =>+ server.is_deployed === true && server.source !== 'smithery' && server.auth_kind !== 'api_key';++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const schemaRefusal = (schema: unknown): ResolveRefusal | null => {+ if (!isRecord(schema)) return null;+ const required = schema.required;+ if (Array.isArray(required) && required.length > 0) return 'requires_input';+ const properties = schema.properties;+ if (isRecord(properties)) {+ for (const property of Object.values(properties)) {+ if (!isRecord(property)) continue;+ if (property['x-secret'] === true || property.isSecret === true) return 'secret_input';+ }+ }+ return null;+};++const urlRefusal = (raw: string | undefined): ResolveRefusal | null => {+ const url = raw?.trim();+ if (!url) return 'missing_url';+ if (TEMPLATE_VAR.test(url)) return 'templated_url';+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return 'invalid_url';+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return 'unsupported_scheme';+ return null;+};++/**+ * The `mcp.json` entry a directory server would be declared with, or why it+ * cannot be declared without the user's input.+ */+export const resolveHostedEntry = (+ detail: SmitheryServerDetail,+ server: SmitheryServer+): ResolveResult => {+ const refuse = (reason: ResolveRefusal): ResolveResult => {+ log('resolve %s refused: %s', server.qualified_name, reason);+ return { ok: false, reason };+ };++ const hosted = (detail.connections ?? []).filter(c => HOSTED_TYPES.has(String(c.type)));+ if (hosted.length === 0) return refuse('no_hosted_connection');++ const urls = new Set<string>();+ for (const connection of hosted) {+ const refusal =+ urlRefusal(connection.deployment_url) ?? schemaRefusal(connection.config_schema);+ if (refusal) return refuse(refusal);+ urls.add((connection.deployment_url as string).trim());+ }+ if (urls.size !== 1) return refuse('multiple_urls');+ if ((detail.required_env_keys ?? []).length > 0) return refuse('requires_env');++ const [url] = urls;+ const description = (server.description ?? detail.description)?.trim();+ return { ok: true, entry: description ? { url, description } : { url } };+};++/**+ * Declare `entry` under `name` in `mcp.json`, keeping every other entry as it+ * is. An existing entry of that name is left untouched. A refusal from the+ * core is rethrown as it came.+ */+export const declareServer = async (name: string, entry: HostedEntry): Promise<DeclareOutcome> => {+ const doc = await mcpClientsApi.configGet();+ const servers = doc.mcpServers ?? {};+ if (Object.prototype.hasOwnProperty.call(servers, name)) {+ log('declare %s skipped: already declared', name);+ return 'exists';+ }+ await mcpClientsApi.configSet({ mcpServers: { ...servers, [name]: entry } });+ log('declare %s added', name);+ return 'added';+};