Skip to content
Open
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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ GITDB_ENCRYPTION_KEY="development"
# /.well-known/oauth-authorization-server answer 404. Manual MCP keys work either way.
# MCP_OAUTH_RESOURCES=https://mcp.cloud.getgitops.com/mcp

# Public URL of the MCP server. When set, the app promotes the MCP ("Connect AI agent" modal, profile
# section, shortcuts) and shows it to users; when empty nothing about MCP is promoted.
# PUBLIC_MCP_URL=https://mcp.cloud.getgitops.com/mcp

# ─── CVE feed (/org/<org>/cves, "CVEs por tecnología" tab; docs/adr/0004-cve-feed.md) ─────────
# Follows the CVEs published in public sources (OSV.dev, NVD, CISA KEV, FIRST EPSS) for the
# technologies each organization chooses, and emits cve_feed.* events. OFF by default: with false
Expand Down
7 changes: 7 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,13 @@ session like any other page. Check it there before inventing a new style.
(`gitops-sidebar-collapsed`); below `md` the sidebar is off-canvas. Auth, bootstrap and `/brand`
keep the bare layout. The sidebar must stay the first `<aside>` in the DOM
(`sidebar-visibility.spec.ts`). Pages inside the shell are still v2 until migrated one by one.
- **MCP promotion:** `PUBLIC_MCP_URL` (public env var, see `.env.example`) turns it on; without it no
modal, menu entry or card is shown. The root `+layout.server.ts` returns `mcpUrl` and `mcpConnected`
(one read through `apiKeysService.hasActiveMcpConnection`, rule in `modules/auth/domain/mcp-connection.ts`:
OAuth key by `refreshExpiresAt`, manual key by `expiresAt`). `ConnectAgentModal`
(`#lib/components/mcp/`) is mounted once in the layout and opened from anywhere with
`openConnectAgent()`. `/profile` has the "Agentes IA conectados" section (OAuth + manual MCP keys),
separate from API keys; revoking asks for confirmation in an `alertdialog`.
- Logo files are in `static/brand/` (`gitops-logo-dark|light.svg`, `gitops-mark-*.svg`,
`gitops-icon.svg` and PNGs). The navbar uses the new logo; the old `gitops_logo*.png`,
`icono_*.png` and `favicon.png` are still used elsewhere (favicon, auth pages).
Expand Down
2 changes: 2 additions & 0 deletions e2e/global-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ function buildEnv(): Record<string, string | undefined> {
GITDB_USERNAME: '',
GITDB_TOKEN: '',
GITDB_PASSWORD: '',
// public MCP URL: turns on the "Connect AI agent" promotion (modal, profile section)
PUBLIC_MCP_URL: 'https://mcp.e2e.test/mcp',
// the suite assumes the CVE feed is off, whatever the developer's `.env` says
CVE_FEED_ENABLED: 'false',
// never reach a real SMTP from a developer's `.env`: the suite runs with email disabled
Expand Down
121 changes: 121 additions & 0 deletions e2e/specs/mcp-connect.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Sección "Agentes IA conectados" del perfil, modal de conexión y badge del menú de cuenta (#142).
// El proyecto admin tiene una clave MCP manual sembrada (e2e-mcp-project-admin) que no se revoca aquí:
// otros specs la usan. Las pruebas de revocar crean su propia clave.
import { test, expect, getSeed } from '../fixtures/auth';

const seed = getSeed();

const MCP_URL = 'https://mcp.e2e.test/mcp';

test.beforeEach(async ({ page, loginAs }) => {
await loginAs('projectAdmin');
await page.goto('/profile');
await page.waitForLoadState('networkidle');
});

test('la sección lista la clave MCP manual y no la mezcla con las claves de API', async ({
page,
}) => {
const agents = page.getByRole('region', { name: 'Agentes IA conectados' });
await expect(agents).toBeVisible();
await expect(agents.getByText('e2e-mcp-project-admin')).toBeVisible();
const apiKeys = page.getByRole('region', { name: 'Claves API' });
await expect(apiKeys.getByText('e2e-mcp-project-admin')).toHaveCount(0);
await expect(apiKeys.getByText('e2e-personal-project-admin')).toBeVisible();
});

test('el menú de cuenta muestra el badge MCP conectado y abre el modal', async ({ page }) => {
await page.getByRole('button', { name: 'Cuenta' }).click();
await expect(page.getByTestId('mcp-connected-badge')).toBeVisible();
await page.getByRole('menuitem', { name: 'Conectar con IA' }).click();

const dialog = page.getByRole('dialog', { name: 'Conecta tu agente de IA' });
await expect(dialog).toBeVisible();
await expect(dialog.getByText(MCP_URL)).toBeVisible();

await dialog.getByRole('tab', { name: 'Claude Code / VS Code' }).click();
await expect(
dialog.getByText(`claude mcp add --transport http --scope user gitops ${MCP_URL}`),
).toBeVisible();
await expect(dialog.getByRole('link', { name: /clave MCP manual/ })).toHaveAttribute(
'href',
'/profile#api-keys',
);

await page.keyboard.press('Escape');
await expect(dialog).toBeHidden();
});

test('el bloque "Conectar un agente" abre el modal y copiar muestra un toast', async ({
page,
context,
}) => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await page.getByTestId('connect-agent').click();
const dialog = page.getByRole('dialog', { name: 'Conecta tu agente de IA' });
await expect(dialog).toBeVisible();
await dialog.getByTestId('copy-url').click();
await expect(page.getByRole('status').filter({ hasText: 'URL copiada' })).toBeVisible();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(MCP_URL);
});

test('revocar una conexión pide confirmación y la quita de la lista', async ({ page }) => {
const name = `e2e-revocar-${Date.now()}`;
await page.getByLabel('Nombre').fill(name);
await page.getByLabel(/Para MCP/).check();
await page.getByRole('button', { name: 'Crear clave API' }).click();

const agents = page.getByRole('region', { name: 'Agentes IA conectados' });
await expect(agents.getByText(name)).toBeVisible();

await agents.getByRole('button', { name: `Revocar la conexión ${name}` }).click();
const confirm = page.getByRole('alertdialog', { name: 'Revocar conexión' });
await expect(confirm).toBeVisible();

// cancelar no revoca
await confirm.getByRole('button', { name: 'Cancelar' }).click();
await expect(confirm).toBeHidden();
await expect(agents.getByText(name)).toBeVisible();

await agents.getByRole('button', { name: `Revocar la conexión ${name}` }).click();
await confirm.getByRole('button', { name: 'Revocar conexión' }).click();
await expect(confirm).toBeHidden();
await expect(agents.getByText(name)).toHaveCount(0);
});

test('la card del dashboard usa slugs reales, no ofrece conectar si ya hay conexión y se puede cerrar', async ({
page,
}) => {
await page.goto(`/org/${seed.primaryOrgSlug}/projects/${seed.primaryProjectSlug}/overview`);
const card = page.getByTestId('ask-agent-card');
await expect(card).toBeVisible();
await expect(card.getByRole('heading', { name: 'Prueba a preguntar…' })).toBeVisible();
await expect(card.getByRole('button', { name: 'Conectar Claude' })).toHaveCount(0);
await expect(card).toContainText(`${seed.primaryOrgSlug}/${seed.primaryProjectSlug}`);

await card.getByRole('button', { name: 'Cerrar sugerencias del agente' }).click();
await expect(card).toBeHidden();
await page.reload();
await page.waitForLoadState('networkidle');
await expect(page.getByTestId('ask-agent-card')).toHaveCount(0);
});

test('el atajo del servicio copia la pregunta con el slug real org/proyecto/servicio', async ({
page,
context,
}) => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await page.goto(
`/org/${seed.primaryOrgSlug}/projects/${seed.primaryProjectSlug}/code-report/services/${seed.seededServiceSlug}`,
);
await page.waitForLoadState('networkidle');
const slug = `${seed.primaryOrgSlug}/${seed.primaryProjectSlug}/${seed.seededServiceSlug}`;
await page.getByTestId('ask-agent-button').click();
const menu = page.getByRole('menu', { name: 'Pregúntale a tu agente' });
await expect(menu).toContainText(`\`${slug}\``);
// ya hay una conexión activa: no se ofrece conectar
await expect(menu.getByRole('menuitem', { name: 'Conectar Claude' })).toHaveCount(0);
await menu.getByRole('menuitem', { name: 'Copiar pregunta' }).click();
await expect(page.getByRole('status').filter({ hasText: 'Pregunta copiada' })).toBeVisible();
expect(await page.evaluate(() => navigator.clipboard.readText())).toContain(`\`${slug}\``);
});
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const variables = defineEnvVars({
MONITORING_INCIDENT_RETENTION_DAYS: optional,
MCP_RATE_LIMIT_PER_MINUTE: optional,
MCP_OAUTH_RESOURCES: optional,
PUBLIC_MCP_URL: { ...optional, public: true },
CVE_FEED_ENABLED: optional,
CVE_FEED_SYNC_INTERVAL: optional,
CVE_FEED_MIN_SEVERITY: optional,
Expand Down
26 changes: 25 additions & 1 deletion src/lib/components/AppNavbar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { onMount } from 'svelte';
import {
BookOpen,
Bot,
Building2,
ChevronDown,
LogOut,
Expand All @@ -21,14 +22,29 @@
user?: NavbarUser | null;
/** Ajustes de GitOps (solo administradores). */
settingsHref?: string | null;
/** Hay URL pública del MCP: se ofrece "Conectar con IA". */
mcpAvailable?: boolean;
/** El usuario tiene una conexión MCP activa. */
mcpConnected?: boolean;
/** Abre el modal de conexión de agentes. */
onconnectagent?: () => void;
/** Abre la búsqueda global. */
onsearch?: () => void;
/** Menú lateral en móvil. */
menuOpen?: boolean;
onmenu?: () => void;
};

let { user = null, settingsHref = null, onsearch, menuOpen = false, onmenu }: Props = $props();
let {
user = null,
settingsHref = null,
mcpAvailable = false,
mcpConnected = false,
onconnectagent,
onsearch,
menuOpen = false,
onmenu,
}: Props = $props();

const roleName = $derived(typeof user?.role === 'string' ? user.role : user?.role?.name);

Expand Down Expand Up @@ -117,9 +133,17 @@
<div class="px-2.5 py-2">
<p class="truncate text-sm font-medium text-white">{user.username}</p>
{#if roleName}<p class="truncate text-xs capitalize text-fg-subtle">{roleName}</p>{/if}
{#if mcpAvailable && mcpConnected}
<span class="k-badge k-badge-ok mt-1.5" data-testid="mcp-connected-badge"
>{$_('nav.mcpConnected')}</span
>
{/if}
</div>
<div class="k-divider my-1" role="separator"></div>
<MenuItem icon={UserRound} href="/profile">{$_('nav.profile')}</MenuItem>
{#if mcpAvailable && onconnectagent}
<MenuItem icon={Bot} onclick={onconnectagent}>{$_('nav.connectAi')}</MenuItem>
{/if}
<MenuItem icon={Building2} href="/org">{$_('nav.changeOrganization')}</MenuItem>
{#if settingsHref}
<MenuItem icon={Settings} href={settingsHref}
Expand Down
5 changes: 5 additions & 0 deletions src/lib/components/code-report/CveDetailView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
Search,
Wrench,
} from '@lucide/svelte';
import AskAgentButton from '#lib/components/mcp/AskAgentButton.svelte';
import {
renderVulnerabilityDescription,
vulnerabilitySourceLabel,
Expand All @@ -72,6 +73,7 @@
showProject = false,
scans = true,
feed,
agentPrompt = null,
}: {
cve: CveDetail;
remediations: CveRemediation[];
Expand All @@ -84,6 +86,8 @@
scans?: boolean;
/** Datos del feed de CVEs (rangos afectados, KEV, referencias), tras la descripción. */
feed?: Snippet;
/** Pregunta contextual para el agente (MCP); sin ella no se muestra el atajo. */
agentPrompt?: string | null;
} = $props();

let query = $state('');
Expand Down Expand Up @@ -174,6 +178,7 @@
{/if}
</div>
<div class="flex flex-wrap items-center gap-2">
{#if agentPrompt}<AskAgentButton prompt={agentPrompt} align="end" />{/if}
{#if cve.cveUrl}
<a
href={cve.cveUrl}
Expand Down
44 changes: 44 additions & 0 deletions src/lib/components/mcp/AskAgentButton.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!--
Botón discreto "Pregúntale a tu agente": abre un menú con la pregunta contextual, "Copiar pregunta"
y, si el usuario no tiene conexión MCP activa, "Conectar Claude" (abre ConnectAgentModal).
No pinta nada si no hay `PUBLIC_MCP_URL` (el layout lo expone como `mcpUrl` en `page.data`).
-->
<script lang="ts">
import { Bot, Copy, Plug } from '@lucide/svelte';
import { page } from '$app/state';
import { DropdownMenu, MenuItem } from '#lib/components/ui';
import { _ } from '#lib/i18n';
import { openConnectAgent } from './connect-agent.svelte';
import { copyToClipboard } from './copy';

type Props = {
/** Pregunta lista para pegar en el agente (ya en el idioma del usuario y con slugs reales). */
prompt: string;
align?: 'start' | 'end';
};

let { prompt, align = 'start' }: Props = $props();

const available = $derived(Boolean(page.data.mcpUrl));
const connected = $derived(Boolean(page.data.mcpConnected));
</script>

{#if available}
<DropdownMenu label={$_('mcp.ask.menu')} {align} class="w-80 p-1.5">
{#snippet trigger(props)}
<button {...props} class="k-btn k-btn-ghost k-btn-sm" data-testid="ask-agent-button">
<Bot class="h-4 w-4" />{$_('mcp.ask.button')}
</button>
{/snippet}
<p class="px-2.5 py-2 text-xs leading-relaxed text-fg-muted">{prompt}</p>
<div class="k-divider my-1" role="separator"></div>
<MenuItem
icon={Copy}
onclick={() => copyToClipboard(prompt, $_('mcp.ask.copied'), $_('mcp.connect.copyFailed'))}
>{$_('mcp.ask.copy')}</MenuItem
>
{#if !connected}
<MenuItem icon={Plug} onclick={openConnectAgent}>{$_('mcp.ask.connect')}</MenuItem>
{/if}
</DropdownMenu>
{/if}
94 changes: 94 additions & 0 deletions src/lib/components/mcp/AskAgentCard.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<!--
Card "Pregúntale a tu agente" (dashboard del proyecto): prompts de ejemplo con botón de copiar y,
si el usuario no tiene conexión MCP activa, el CTA "Conectar Claude". Se puede cerrar; la elección
se guarda en localStorage (solo comodidad del navegador).
-->
<script lang="ts">
import { onMount } from 'svelte';
import { Bot, Copy, X } from '@lucide/svelte';
import { _ } from '#lib/i18n';
import type { AgentPrompt } from '#lib/mcp/prompts';
import { openConnectAgent } from './connect-agent.svelte';
import { copyToClipboard } from './copy';

type Props = { prompts: AgentPrompt[]; connected: boolean };

let { prompts, connected }: Props = $props();

const DISMISSED_KEY = 'gitops-mcp-card-dismissed';
// oculta hasta montar: así quien la cerró no la ve parpadear y no hay lectura en el servidor
let ready = $state(false);
let dismissed = $state(false);

onMount(() => {
try {
dismissed = localStorage.getItem(DISMISSED_KEY) === '1';
} catch {
// sin almacenamiento: la card se muestra
}
ready = true;
});

function dismiss() {
dismissed = true;
try {
localStorage.setItem(DISMISSED_KEY, '1');
} catch {
// solo se cierra en esta sesión
}
}
</script>

{#if ready && !dismissed && prompts.length > 0}
<section
class="k-card relative p-5"
aria-labelledby="ask-agent-title"
data-testid="ask-agent-card"
>
<button
type="button"
class="k-btn k-btn-ghost k-btn-icon k-btn-sm absolute right-3 top-3"
aria-label={$_('mcp.card.dismiss')}
onclick={dismiss}
>
<X class="h-4 w-4" />
</button>
<div class="flex flex-wrap items-start justify-between gap-3 pr-10">
<div class="flex items-start gap-3">
<Bot class="mt-0.5 h-4 w-4 text-brand-400" />
<div>
<h2 id="ask-agent-title" class="text-sm font-semibold text-white">
{connected ? $_('mcp.card.titleTry') : $_('mcp.card.titleConnect')}
</h2>
<p class="text-xs text-fg-subtle">
{connected ? $_('mcp.card.descriptionTry') : $_('mcp.card.descriptionConnect')}
</p>
</div>
</div>
{#if !connected}
<button type="button" class="k-btn k-btn-primary k-btn-sm" onclick={openConnectAgent}>
{$_('mcp.card.connect')}
</button>
{/if}
</div>
<ul class="mt-4 space-y-2">
{#each prompts as prompt (prompt.id)}
<li
class="flex items-center justify-between gap-3 rounded-xl border border-white/8 bg-ink-950/60 px-3.5 py-2.5"
>
<p class="min-w-0 text-sm text-fg">{prompt.text}</p>
<button
type="button"
class="k-btn k-btn-ghost k-btn-icon k-btn-sm shrink-0"
aria-label={$_('mcp.card.copy')}
title={$_('mcp.card.copy')}
onclick={() =>
copyToClipboard(prompt.text, $_('mcp.card.copied'), $_('mcp.connect.copyFailed'))}
>
<Copy class="h-4 w-4" />
</button>
</li>
{/each}
</ul>
</section>
{/if}
Loading
Loading