fix: mcp agent policies and deduplicate blocks when merging unrolled assistants (#8376)

* fix: deduplicate blocks when merging config yaml

* fix: tool policies for mcp servers in agent mode

* fix: syntax error

* fix: cli tests

* fix: don't log

* fix: lint/format

* fix: better comments for tool policies

* fix: one test left

* fix: failing services test

* fix: lint and format
This commit is contained in:
Dallin Romney 2025-10-22 14:41:41 -07:00 • committed by GitHub
parent 749916dcbf
commit 5fa2415e9b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 772 additions and 121 deletions

View file

@ -108,11 +108,8 @@ name: "Incomplete Config"
});
test("should handle empty string config path", async () => {
// Empty string should be treated differently from undefined
// Note: empty string triggers onboarding flow, but should still fail in our error format
await expect(
initializeWithOnboarding(mockAuthConfig, ""),
).rejects.toThrow();
// Loads default agent with no error
await initializeWithOnboarding(mockAuthConfig, "");
});
test("should not fall back to default config when explicit config fails", async () => {

View file

@ -52,7 +52,7 @@ export class MCPService
private isShuttingDown = false;
getDependencies(): string[] {
return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.CONFIG];
return [SERVICE_NAMES.CONFIG];
}
constructor() {
super("MCPService", {

View file

@ -1,4 +1,4 @@
import { parseAgentFileTools } from "@continuedev/config-yaml";
import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js";
import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js";
import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js";
@ -11,7 +11,11 @@ import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { AgentFileServiceState, SERVICE_NAMES } from "./types.js";
import {
AgentFileServiceState,
MCPServiceState,
SERVICE_NAMES,
} from "./types.js";
export interface InitializeToolServiceOverrides {
allow?: string[];
@ -61,55 +65,94 @@ export class ToolPermissionService
* Declare dependencies on other services
*/
getDependencies(): string[] {
return [SERVICE_NAMES.AGENT_FILE];
return [SERVICE_NAMES.AGENT_FILE, SERVICE_NAMES.MCP];
}
/**
* Generate agent-file-specific policies if an agent file is active
*/
private generateAgentFilePolicies(
generateAgentFilePolicies(
agentFileServiceState?: AgentFileServiceState,
mcpServiceState?: MCPServiceState,
): undefined | ToolPermissionPolicy[] {
if (!agentFileServiceState?.agentFile?.tools) {
const parsedTools = agentFileServiceState?.parsedTools;
if (!parsedTools?.tools.length) {
return undefined;
}
const parsedTools = parseAgentFileTools(
agentFileServiceState.agentFile.tools,
);
if (parsedTools.tools.length === 0) {
return undefined;
}
const policies: ToolPermissionPolicy[] = [];
const servers = Array.from(mcpServiceState?.connections?.values() ?? []);
for (const mcpServer of parsedTools.mcpServers) {
const server = servers?.find(
(s) => s.config?.sourceSlug && s.config.sourceSlug === mcpServer,
);
if (!server) {
logger.warn("No connected MCP server found ");
continue;
}
for (const toolRef of parsedTools.tools) {
if (toolRef.mcpServer) {
if (toolRef.toolName) {
policies.push({
tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`,
permission: "allow",
});
} else {
policies.push({
tool: `mcp:${toolRef.mcpServer}:*`,
permission: "allow",
});
}
} else if (toolRef.toolName) {
policies.push({ tool: toolRef.toolName, permission: "allow" });
const specificTools = parsedTools.tools.filter(
(t) => t.mcpServer && t.toolName && t.mcpServer === mcpServer,
);
// In the `tools` key of an agent is comma separated strings like
// mcp/server, mcp/server2:tool_name, Bash
// - this would give the agent access to ALL tools from mcp/server, ONLY tool_name from mcp/server2, and Bash, and no other tools
// mcp/server
// - this would give the agent access to ALL tools from mcp/server, and no built-ins
// built_in, mcp/server
// - "built_in" keyword can be used to include all built ins
// Blank = all built-in tools
// Handle MCP first
// If ANY mcp tools are specifically called out, only allow those ones for that mcp server
// Otherwise the blanket allow will cover all MCP tools
if (specificTools.length) {
const specificSet = new Set(specificTools.map((t) => t.toolName));
const notMentioned = server.tools.filter(
(t) => !specificSet.has(t.name),
);
const allowed: ToolPermissionPolicy[] = specificTools.map((t) => ({
tool: t.toolName!,
permission: "allow",
}));
policies.push(...allowed);
const disallowed: ToolPermissionPolicy[] = notMentioned.map((t) => ({
tool: t.name,
permission: "exclude",
}));
policies.push(...disallowed);
}
}
if (policies.length > 0) {
logger.debug(`Generated ${policies.length} agent file tool policies`);
// If mcp servers or specific built-in tools are specified
// then we only inclue listed built-in tools and exclude all others
const hasMcp = !!parsedTools.mcpServers?.length;
const specificBuiltIns = parsedTools.tools
.filter((t) => !t.mcpServer)
.map((t) => t.toolName!);
if (specificBuiltIns.length || (hasMcp && !parsedTools.allBuiltIn)) {
const allowed: ToolPermissionPolicy[] = specificBuiltIns.map((tool) => ({
tool,
permission: "allow",
}));
policies.push(...allowed);
const specificBuiltInSet = new Set(specificBuiltIns);
const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter(
(name) => !specificBuiltInSet.has(name),
);
const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({
tool,
permission: "exclude",
}));
policies.push(...disallowed);
}
if (parsedTools.allBuiltIn) {
policies.push({ tool: "*", permission: "allow" });
policies.push({ tool: "mcp:*", permission: "exclude" });
} else {
policies.push({ tool: "*", permission: "exclude" });
}
// Allow all other tools
policies.push({
tool: "*",
permission: "allow",
});
return policies;
}
@ -165,6 +208,7 @@ export class ToolPermissionService
initializeSync(
runtimeOverrides?: InitializeToolServiceOverrides,
agentFileServiceState?: AgentFileServiceState,
mcpServiceState?: MCPServiceState,
): ToolPermissionServiceState {
logger.debug("Synchronously initializing ToolPermissionService");
@ -180,6 +224,7 @@ export class ToolPermissionService
const agentFilePolicies = this.generateAgentFilePolicies(
agentFileServiceState,
mcpServiceState,
);
const modePolicies = this.generateModePolicies();
@ -224,11 +269,16 @@ export class ToolPermissionService
async doInitialize(
runtimeOverrides?: InitializeToolServiceOverrides,
agentFileServiceState?: AgentFileServiceState,
mcpServiceState?: MCPServiceState,
): Promise<ToolPermissionServiceState> {
await ensurePermissionsYamlExists();
// Use the synchronous version after ensuring the file exists
return this.initializeSync(runtimeOverrides, agentFileServiceState);
return this.initializeSync(
runtimeOverrides,
agentFileServiceState,
mcpServiceState,
);
}
/**

View file

@ -1,71 +1,10 @@
import { Configuration, DefaultApi } from "@continuedev/sdk/dist/api";
import { vi } from "vitest";
import { MCPService } from "./MCPService.js";
import { initializeServices, services } from "./index.js";
// Mock the onboarding module
vi.mock("../onboarding.js", () => ({
initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }),
createOrUpdateConfig: vi.fn().mockResolvedValue(undefined),
}));
// Mock auth module
vi.mock("../auth/workos.js", () => ({
loadAuthConfig: vi.fn().mockReturnValue({}),
getConfigUri: vi.fn().mockReturnValue(null),
}));
// Mock the config loader
vi.mock("../configLoader.js", () => ({
loadConfiguration: vi.fn().mockResolvedValue({
config: { name: "test", version: "1.0.0" },
source: { type: "test" },
}),
}));
describe("initializeServices", () => {
// let mockToolPermissionsService: any;
beforeEach(() => {
// Reset all mocks
vi.clearAllMocks();
// Mock service methods to avoid actual initialization
vi.spyOn(services.auth, "initialize").mockResolvedValue({
authConfig: {
accessToken: "",
expiresAt: 123,
organizationId: "",
refreshToken: "",
userEmail: "",
},
isAuthenticated: false,
});
vi.spyOn(services.apiClient, "initialize").mockResolvedValue({
apiClient: new DefaultApi(
new Configuration({
basePath: "",
accessToken: "",
}),
),
});
vi.spyOn(services.agentFile, "initialize").mockResolvedValue({
slug: null,
agentFile: null,
agentFileModel: null,
parsedRules: null,
parsedTools: null,
});
vi.spyOn(services.config, "initialize").mockResolvedValue({
config: { name: "test", version: "1.0.0" },
configPath: undefined,
});
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("mode conversion", () => {
it("should pass only auto flag for auto mode", async () => {
const spy = vi.spyOn(services.toolPermissions, "initialize");
@ -94,6 +33,12 @@ describe("initializeServices", () => {
parsedRules: null,
parsedTools: null,
},
{
connections: [],
mcpService: expect.any(MCPService),
prompts: [],
tools: [],
},
);
});
});

View file

@ -113,9 +113,10 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
serviceContainer.register(
SERVICE_NAMES.TOOL_PERMISSIONS,
async () => {
const agentFileState = await serviceContainer.get<AgentFileServiceState>(
SERVICE_NAMES.AGENT_FILE,
);
const [mcpState, agentFileState] = await Promise.all([
serviceContainer.get<AuthServiceState>(SERVICE_NAMES.MCP),
serviceContainer.get<AgentFileServiceState>(SERVICE_NAMES.AGENT_FILE),
]);
// Initialize mode service with tool permission overrides
if (initOptions.toolPermissionOverrides) {
@ -128,13 +129,16 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
exclude: overrides.exclude,
isHeadless: initOptions.headless,
};
// Only set the boolean flag that corresponds to the mode
if (overrides.mode) {
initArgs.mode = overrides.mode;
}
// If mode is "normal" or undefined, no flags are set
return await toolPermissionService.initialize(initArgs, agentFileState);
return await toolPermissionService.initialize(
initArgs,
agentFileState,
mcpState,
);
} else {
// Even if no overrides, we need to initialize with defaults
return await toolPermissionService.initialize(
@ -142,10 +146,11 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
isHeadless: initOptions.headless,
},
agentFileState,
mcpState,
);
}
},
[SERVICE_NAMES.AGENT_FILE],
[SERVICE_NAMES.AGENT_FILE, SERVICE_NAMES.MCP],
);
// Initialize SystemMessageService with command options
@ -257,7 +262,10 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
if (!configState.config) {
throw new Error("Config not available for MCP service");
}
return mcpService.initialize(configState.config, initOptions.headless);
return mcpService.initialize(
configState.config,
initOptions.headless || initOptions.options?.agent,
);
},
[SERVICE_NAMES.CONFIG], // Depends on config
);

View file

@ -0,0 +1,26 @@
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
import { listFilesTool } from "./listFiles.js";
import { multiEditTool } from "./multiEdit.js";
import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
import { searchCodeTool } from "./searchCode.js";
import { statusTool } from "./status.js";
import { writeChecklistTool } from "./writeChecklist.js";
import { writeFileTool } from "./writeFile.js";
// putting in here for circular import issue
export const ALL_BUILT_IN_TOOLS = [
readFileTool,
editTool,
multiEditTool,
writeFileTool,
listFilesTool,
searchCodeTool,
runTerminalCommandTool,
fetchTool,
writeChecklistTool,
exitTool,
statusTool,
];

View file

@ -6,6 +6,43 @@ import { resetConsoleOverrides } from "./src/init.js";
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";
process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0";
// Mock fetch to prevent actual API calls in tests
const originalFetch = global.fetch;
global.fetch = vi
.fn()
.mockImplementation(async (url: string | URL, ...args) => {
const urlString = url.toString();
// Mock the default-agent API call
if (urlString.includes("get-assistant/continuedev/default-agent")) {
return {
ok: true,
status: 200,
json: async () => ({
configResult: {
config: {
name: "Default Agent",
version: "0.0.1",
schema: "v1",
models: [
{
provider: "anthropic",
name: "claude-sonnet-4-5",
apiKey: "test-key",
roles: ["chat"],
},
],
rules: [],
mcpServers: [],
},
errors: [],
},
}),
};
}
return originalFetch(url, ...args);
});
// Mock the 'open' package to prevent browser opening during tests
vi.mock("open", () => ({
default: vi.fn().mockResolvedValue(undefined),

View file

@ -1,5 +1,6 @@
import { RequestOptions } from "../browser.js";
import { BLOCK_TYPES, RequestOptions } from "../browser.js";
import { AssistantUnrolled, ConfigYaml } from "../schemas/index.js";
import { BlockDuplicationDetector } from "./blockDuplicationDetector.js";
export function mergePackages(
current: ConfigYaml,
@ -26,21 +27,35 @@ export function mergeUnrolledAssistants(
current: AssistantUnrolled,
incoming: AssistantUnrolled,
): AssistantUnrolled {
return {
const assistant: AssistantUnrolled = {
...current,
rules: [...(current.rules ?? []), ...(incoming.rules ?? [])],
models: [...(current.models ?? []), ...(incoming.models ?? [])],
docs: [...(current.docs ?? []), ...(incoming.docs ?? [])],
context: [...(current.context ?? []), ...(incoming.context ?? [])],
data: [...(current.data ?? []), ...(incoming.data ?? [])],
mcpServers: [...(current.mcpServers ?? []), ...(incoming.mcpServers ?? [])],
prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])],
env: { ...current.env, ...incoming.env },
requestOptions: mergeConfigYamlRequestOptions(
current.requestOptions,
incoming.requestOptions,
),
};
const duplicationDetector = new BlockDuplicationDetector();
for (const blockType of BLOCK_TYPES) {
const allOfType = [
...(incoming[blockType] ?? []),
...(current[blockType] ?? []),
];
const deduplicated: typeof allOfType = [];
for (const block of allOfType) {
if (block && !duplicationDetector.isDuplicated(block, blockType)) {
deduplicated.push(block);
}
}
if (deduplicated.length > 0) {
assistant[blockType] = deduplicated as any;
} else {
assistant[blockType] = undefined;
}
}
return assistant;
}
export function mergeConfigYamlRequestOptions(

View file

@ -0,0 +1,562 @@
import { describe, expect, it } from "@jest/globals";
import { AssistantUnrolled } from "../schemas/index.js";
import { mergeUnrolledAssistants } from "./merge.js";
describe("mergeUnrolledAssistants", () => {
const createBaseConfig = (): AssistantUnrolled => ({
name: "Base Assistant",
version: "1.0.0",
models: [
{
name: "gpt-4",
model: "gpt-4",
provider: "openai",
},
],
context: [
{
provider: "file",
},
],
rules: [
{
name: "typescript-style",
rule: "Use TypeScript best practices",
},
],
prompts: [
{
name: "code-review",
description: "Review code for best practices",
prompt: "Please review this code",
},
],
docs: [
{
name: "api-docs",
startUrl: "https://api.example.com/docs",
},
],
data: [
{
name: "user-data",
destination: "memory",
schema: "0.1.0",
},
],
mcpServers: [
{
name: "filesystem",
command: "npx",
args: ["@modelcontextprotocol/server-filesystem"],
env: {
ROOT_PATH: "/tmp",
},
},
],
env: {
API_KEY: "base-key",
},
requestOptions: {
timeout: 5000,
headers: {
"X-Base": "value",
},
},
});
const createIncomingConfig = (): AssistantUnrolled => ({
name: "Incoming Assistant",
version: "1.1.0",
models: [
{
name: "gpt-3.5-turbo",
model: "gpt-3.5-turbo",
provider: "openai",
},
],
context: [
{
provider: "git",
},
],
rules: [
{
name: "code-formatting",
rule: "Use Prettier for code formatting",
},
],
prompts: [
{
name: "bug-fix",
description: "Fix bugs in code",
prompt: "Please fix the bug in this code",
},
],
docs: [
{
name: "user-guide",
startUrl: "https://docs.example.com/guide",
},
],
data: [
{
name: "project-data",
destination: "filesystem",
schema: "0.1.0",
},
],
mcpServers: [
{
name: "git-server",
command: "npx",
args: ["@modelcontextprotocol/server-git"],
},
],
env: {
API_TOKEN: "incoming-token",
API_KEY: "incoming-key", // This will override base via object spread
},
requestOptions: {
timeout: 3000,
headers: {
"X-Incoming": "value",
"X-Base": "overridden",
},
},
});
it("should merge all block types without duplicates", () => {
const base = createBaseConfig();
const incoming = createIncomingConfig();
const result = mergeUnrolledAssistants(base, incoming);
// Should have models from both configs (incoming first due to priority)
expect(result.models).toHaveLength(2);
expect(result.models?.map((m) => m?.name)).toEqual([
"gpt-3.5-turbo",
"gpt-4",
]);
// Should have context from both configs (incoming first due to priority)
expect(result.context).toHaveLength(2);
expect(result.context?.map((c) => c?.provider)).toEqual(["git", "file"]);
// Should have rules from both configs (incoming first due to priority)
expect(result.rules).toHaveLength(2);
expect(
result.rules?.map((r) => (typeof r === "string" ? r : r?.name)),
).toEqual(["code-formatting", "typescript-style"]);
// Should have prompts from both configs (incoming first due to priority)
expect(result.prompts).toHaveLength(2);
expect(result.prompts?.map((p) => p?.name)).toEqual([
"bug-fix",
"code-review",
]);
// Should have docs from both configs (incoming first due to priority)
expect(result.docs).toHaveLength(2);
expect(result.docs?.map((d) => d?.name)).toEqual([
"user-guide",
"api-docs",
]);
// Should have data from both configs (incoming first due to priority)
expect(result.data).toHaveLength(2);
expect(result.data?.map((d) => d?.name)).toEqual([
"project-data",
"user-data",
]);
// Should have mcpServers from both configs (incoming first due to priority)
expect(result.mcpServers).toHaveLength(2);
expect(result.mcpServers?.map((s) => s?.name)).toEqual([
"git-server",
"filesystem",
]);
});
it("should deduplicate models by name", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
models: [
{
name: "gpt-4", // Duplicate name
model: "gpt-4",
provider: "openai",
},
{
name: "claude-3",
model: "claude-3-sonnet-20240229",
provider: "anthropic",
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 models (incoming gpt-4 and incoming claude-3)
expect(result.models).toHaveLength(2);
expect(result.models?.map((m) => m?.name)).toEqual(["gpt-4", "claude-3"]);
// Should keep the incoming version of gpt-4 (base version filtered as duplicate)
expect(result.models?.[0]?.model).toBe("gpt-4");
});
it("should deduplicate context by provider", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
context: [
{
name: "file-context", // Different name but same provider
provider: "file", // Same provider as base
},
{
name: "terminal",
provider: "terminal",
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 context providers (incoming file and incoming terminal)
expect(result.context).toHaveLength(2);
expect(result.context?.map((c) => c?.provider)).toEqual([
"file",
"terminal",
]);
// Should keep the incoming version of file provider (base version filtered as duplicate)
expect(result.context?.[0]?.name).toBe("file-context");
});
it("should deduplicate rules by name", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
rules: [
{
name: "typescript-style", // Duplicate name
rule: "Use different TypeScript practices",
},
{
name: "naming-convention",
rule: "Use camelCase for variables",
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 rules (incoming typescript-style and incoming naming-convention)
expect(result.rules).toHaveLength(2);
expect(
result.rules?.map((r) => (typeof r === "string" ? r : r?.name)),
).toEqual(["typescript-style", "naming-convention"]);
// Should keep the incoming version of typescript-style (base version filtered as duplicate)
const typescriptRule = result.rules?.[0] as any;
expect(typescriptRule.rule).toBe("Use different TypeScript practices");
});
it("should deduplicate string rules", () => {
const base: AssistantUnrolled = {
name: "Base Assistant",
version: "1.0.0",
rules: ["Use semicolons", "Format with Prettier"],
};
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
rules: [
"Use semicolons", // Duplicate
"Use const instead of let",
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 3 unique rules (incoming first, then non-duplicates from base)
expect(result.rules).toHaveLength(3);
expect(result.rules).toEqual([
"Use semicolons",
"Use const instead of let",
"Format with Prettier",
]);
});
it("should deduplicate prompts by name", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
prompts: [
{
name: "code-review", // Duplicate name
description: "Different review process",
prompt: "Different review prompt",
},
{
name: "documentation",
description: "Generate documentation",
prompt: "Create docs for this code",
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 prompts (incoming code-review and incoming documentation)
expect(result.prompts).toHaveLength(2);
expect(result.prompts?.map((p) => p?.name)).toEqual([
"code-review",
"documentation",
]);
// Should keep the incoming version of code-review (base version filtered as duplicate)
expect(result.prompts?.[0]?.description).toBe("Different review process");
});
it("should deduplicate docs by name", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
docs: [
{
name: "api-docs", // Duplicate name
startUrl: "https://different-api.example.com/docs",
},
{
name: "tutorials",
startUrl: "https://tutorials.example.com",
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 docs (incoming api-docs and incoming tutorials)
expect(result.docs).toHaveLength(2);
expect(result.docs?.map((d) => d?.name)).toEqual(["api-docs", "tutorials"]);
// Should keep the incoming version of api-docs (base version filtered as duplicate)
expect(result.docs?.[0]?.startUrl).toBe(
"https://different-api.example.com/docs",
);
});
it("should deduplicate data by name", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
data: [
{
name: "user-data", // Duplicate name
destination: "different-provider",
schema: "0.1.0",
},
{
name: "system-data",
destination: "system",
schema: "0.1.0",
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 data sources (incoming user-data and incoming system-data)
expect(result.data).toHaveLength(2);
expect(result.data?.map((d) => d?.name)).toEqual([
"user-data",
"system-data",
]);
// Should keep the incoming version of user-data (base version filtered as duplicate)
expect(result.data?.[0]?.destination).toBe("different-provider");
});
it("should deduplicate mcpServers by name", () => {
const base = createBaseConfig();
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
mcpServers: [
{
name: "filesystem", // Duplicate name
command: "different-command",
args: ["different-args"],
},
{
name: "database",
command: "db-server",
args: ["--port", "5432"],
},
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should only have 2 MCP servers (incoming filesystem and incoming database)
expect(result.mcpServers).toHaveLength(2);
expect(result.mcpServers?.map((s) => s?.name)).toEqual([
"filesystem",
"database",
]);
// Should keep the incoming version of filesystem (base version filtered as duplicate)
const firstMcpServer = result.mcpServers?.[0];
if (firstMcpServer && "command" in firstMcpServer) {
expect(firstMcpServer.command).toBe("different-command");
}
});
it("should handle null values in arrays", () => {
const base: AssistantUnrolled = {
name: "Base Assistant",
version: "1.0.0",
models: [
null,
{
name: "gpt-4",
model: "gpt-4",
provider: "openai",
},
],
};
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
models: [
{
name: "claude-3",
model: "claude-3-sonnet-20240229",
provider: "anthropic",
},
null,
],
};
const result = mergeUnrolledAssistants(base, incoming);
// Should filter out null values and have only 2 models (incoming first due to priority)
expect(result.models).toHaveLength(2);
expect(result.models?.map((m) => m?.name)).toEqual(["claude-3", "gpt-4"]);
});
it("should merge env variables with incoming overriding base", () => {
const base = createBaseConfig();
const incoming = createIncomingConfig();
const result = mergeUnrolledAssistants(base, incoming);
expect(result.env).toEqual({
API_KEY: "incoming-key", // Should be overridden by incoming
API_TOKEN: "incoming-token", // New from incoming
});
});
it("should merge requestOptions correctly", () => {
const base = createBaseConfig();
const incoming = createIncomingConfig();
const result = mergeUnrolledAssistants(base, incoming);
expect(result.requestOptions).toEqual({
timeout: 5000, // Base overrides incoming
headers: {
"X-Base": "value", // Base overrides incoming in headers too
"X-Incoming": "value", // New from incoming
},
});
});
it("should handle empty arrays and undefined fields", () => {
const base: AssistantUnrolled = {
name: "Base Assistant",
version: "1.0.0",
models: [],
context: undefined,
};
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
models: [
{
name: "gpt-4",
model: "gpt-4",
provider: "openai",
},
],
rules: [],
};
const result = mergeUnrolledAssistants(base, incoming);
expect(result.models).toHaveLength(1);
expect(result.models?.[0]?.name).toBe("gpt-4");
expect(result.context).toBeUndefined();
expect(result.rules).toBeUndefined();
});
it("should preserve name and version from base config", () => {
const base = createBaseConfig();
const incoming = createIncomingConfig();
const result = mergeUnrolledAssistants(base, incoming);
expect(result.name).toBe("Base Assistant");
expect(result.version).toBe("1.0.0");
});
it("should handle complex deduplication scenario with mixed types", () => {
const base: AssistantUnrolled = {
name: "Base Assistant",
version: "1.0.0",
rules: [
"Simple rule 1",
{
name: "complex-rule",
rule: "Complex rule description",
},
"Simple rule 2",
],
};
const incoming: AssistantUnrolled = {
name: "Incoming Assistant",
version: "1.1.0",
rules: [
"Simple rule 1", // Duplicate
{
name: "complex-rule", // Duplicate by name
rule: "Different complex rule description",
},
{
name: "new-complex-rule",
rule: "New complex rule",
},
"Simple rule 3",
],
};
const result = mergeUnrolledAssistants(base, incoming);
expect(result.rules).toHaveLength(5); // 4 incoming + 1 from base (2 duplicates filtered)
expect(result.rules).toEqual([
"Simple rule 1", // From incoming (base duplicate filtered)
{
name: "complex-rule",
rule: "Different complex rule description", // Should keep incoming version
},
{
name: "new-complex-rule",
rule: "New complex rule",
},
"Simple rule 3",
"Simple rule 2", // From base (only non-duplicate left)
]);
});
});

View file

@ -721,7 +721,17 @@ export async function resolveBlock(
secrets: extractFQSNMap(rawYaml, [id]),
});
return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
// Add source slug for mcp servers
const parsed = parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
if (
id.uriType === "slug" &&
"mcpServers" in parsed &&
parsed.mcpServers?.[0]
) {
parsed.mcpServers[0].sourceSlug = `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`;
}
return parsed;
}
export function parseMarkdownRuleOrAssistantUnrolled(

View file

@ -6,6 +6,7 @@ const baseMcpServerSchema = z.object({
serverName: z.string().optional(),
faviconUrl: z.string().optional(),
sourceFile: z.string().optional(), // Added during loading
sourceSlug: z.string().optional(), // Added during loading
connectionTimeout: z.number().gt(0).optional(),
});