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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ GITOPS_API_URL=https://cloud.getgitops.com
GITOPS_API_TIMEOUT_MS=10000
# debug | info | warn | error | silent
LOG_LEVEL=info
# URL pública del endpoint MCP (opcional); activa la discovery OAuth (Claude.ai). Sin barra final
# MCP_PUBLIC_URL=https://mcp.cloud.getgitops.com/mcp
# Issuer OAuth de GitOps (opcional); por defecto GITOPS_API_URL
# GITOPS_AUTH_SERVER_URL=https://cloud.getgitops.com
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Servidor MCP stateless de GitOps (ADR 0005 en el repo `gitops`). Es un cliente d
## Estructura

- `src/config.ts`: variables de entorno. `src/log.ts`: logs JSON con campos cerrados (`LogFields`).
- `src/http.ts`: servidor HTTP (`/mcp`, `/healthz`, auth Bearer, un server+transport por petición). `src/server.ts`: crea el `McpServer`.
- `src/http.ts`: servidor HTTP (`/mcp`, `/healthz`, metadata OAuth, un server+transport por petición). `src/auth.ts`: `TokenValidator` (valida contra `/api/whoami` con caché), `WWW-Authenticate`, metadata RFC 9728 y CORS. `src/server.ts`: crea el `McpServer`.
- `src/api/client.ts`: `GitOpsApiClient` (`get`, `post`, `fetchAll`), `GitOpsApiError`. `src/api/types.ts`: tipos de las respuestas de la API.
- `src/resolve.ts`: `resolveProject`, `resolveService`, `resolveOrganization` (slug o id, caché por petición).
- `src/tools/{code-report,cves,monitoring}.ts`: un `registerXTools(server, ctx)` por área. `src/tools/context.ts`: `ToolContext` y `runTool`. `src/tools/result.ts`: `toolResult`, `toolError`.
Expand Down
37 changes: 28 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,36 @@ Diseño completo: ADR 0005 (`docs/adr/0005-mcp-server.md` en el repo `gitops`).

```
Claude Code ──MCP (HTTP + Bearer gvs_…)──▶ gitops-mcp ──REST + mismo Bearer──▶ GitOps API ──▶ GitDB
(sin estado) (permisos, auditoría,
vault bloqueado)
Claude.ai ──MCP (HTTP + Bearer OAuth)──▶ (sin estado) (permisos, auditoría,
│ vault bloqueado,
└──── OAuth 2.1 (login + consentimiento) ──────────────────────────────▶ Authorization Server)
```

- **OAuth (Claude.ai):** gitops-mcp es solo el _Resource Server_. GitOps es el _Authorization Server_ y emite como access token una clave `gvs_…` normal (audience mcp, caduca en 1 h, con refresh). gitops-mcp publica la metadata de recurso protegido (RFC 9728) para que el cliente descubra dónde autenticarse.

- **Sin acceso a GitDB, sin credenciales propias, sin estado.** Cada tool son una o varias llamadas REST a `/api/...` reenviando la cabecera `Authorization` del usuario tal cual. Permisos, auditoría y rate limit viven en la API: el MCP no puede hacer nada que el usuario no pueda hacer en la UI.
- **Transporte:** Streamable HTTP en modo stateless (un server + transport nuevo por petición, sin `Mcp-Session-Id`). Cualquier réplica atiende cualquier petición.
- **Sin vault:** no hay ninguna tool de secretos ni una tool genérica "llama a cualquier endpoint".
- No se guarda ni se loguea el token, las cabeceras, los argumentos ni los cuerpos de respuesta.

## Variables de entorno

| Variable | Por defecto | Descripción |
| ----------------------- | ------------- | ------------------------------------------- |
| `GITOPS_API_URL` | (obligatoria) | URL base de la API de GitOps |
| `PORT` | `3000` | Puerto HTTP |
| `GITOPS_API_TIMEOUT_MS` | `10000` | Timeout de cada petición a la API |
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` o `silent` |
| Variable | Por defecto | Descripción |
| ------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `GITOPS_API_URL` | (obligatoria) | URL base de la API de GitOps |
| `PORT` | `3000` | Puerto HTTP |
| `GITOPS_API_TIMEOUT_MS` | `10000` | Timeout de cada petición a la API |
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` o `silent` |
| `MCP_PUBLIC_URL` | (vacía) | URL pública del endpoint MCP, p. ej. `https://mcp.cloud.getgitops.com/mcp`, sin barra final. Activa la discovery OAuth; sin ella, desactivada |
| `GITOPS_AUTH_SERVER_URL` | `GITOPS_API_URL` | Issuer OAuth de GitOps (Authorization Server) que se anuncia en la metadata |

Ver `.env.example`.

## Endpoints

- `POST /mcp`: protocolo MCP. Requiere `Authorization: Bearer gvs_…` (si no, 401 con `WWW-Authenticate: Bearer realm="gitops-mcp"`).
- `POST /mcp`: protocolo MCP. Requiere `Authorization: Bearer gvs_…` (clave MCP manual o access token OAuth). Antes de atender la petición se valida el token con `GET /api/whoami` de GitOps (caché en memoria de 60 s, solo aciertos, clave = sha256 de la cabecera). Si falta o no es válido: HTTP 401 con `WWW-Authenticate: Bearer realm="gitops-mcp", resource_metadata="<origen>/.well-known/oauth-protected-resource/mcp"` (sin `MCP_PUBLIC_URL`, solo `Bearer realm="gitops-mcp"`). Si GitOps limita (429) se devuelve 429 con `Retry-After`; si no responde (red/5xx), 503 sin invalidar el token del cliente.
- `OPTIONS /mcp`: preflight CORS (204). `/mcp` responde con `Access-Control-Allow-Origin: *` y expone `WWW-Authenticate` (clientes de navegador como MCP Inspector).
- `GET /.well-known/oauth-protected-resource` y `/.well-known/oauth-protected-resource/mcp`: metadata RFC 9728 (`resource`, `authorization_servers`, `bearer_methods_supported`, `scopes_supported`, `resource_name`) con CORS. Solo con `MCP_PUBLIC_URL`; si no, 404.
- `GET /mcp` y `DELETE /mcp`: 405 (modo stateless).
- `GET /healthz`: `200 {"ok":true}`.

Expand Down Expand Up @@ -83,6 +90,18 @@ docker run --rm -p 3000:3000 -e GITOPS_API_URL=https://cloud.getgitops.com gitop

4. Pregunta, por ejemplo: "¿qué proyectos tengo en GitOps?".

## Uso desde Claude.ai (conector OAuth)

Claude.ai exige OAuth 2.1 para los conectores personalizados (el servidor debe tener `MCP_PUBLIC_URL` configurada):

1. **Ajustes → Conectores → Añadir conector personalizado**.
2. URL: `https://mcp.cloud.getgitops.com/mcp`.
3. Inicia sesión en GitOps y acepta el consentimiento.

La conexión aparece en **/profile** como clave MCP "OAuth" y se revoca desde allí. El access token caduca en 1 h y Claude.ai lo refresca solo.

Claude Code sigue pudiendo usar la clave manual con cabecera `Authorization: Bearer gvs_…` (ver arriba): OAuth se añade, no sustituye.

Las tools aceptan referencias legibles: `org/proyecto`, `proyecto` (si es único) o `org/proyecto/servicio`, además de ids.

## Tools
Expand Down
122 changes: 122 additions & 0 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { createHash } from 'node:crypto';
import type { ServerResponse } from 'node:http';
import { GitOpsApiClient, GitOpsApiError } from './api/client.js';
import type { Config } from './config.js';

const WHOAMI_PATH = '/api/whoami';
const CACHE_TTL_MS = 60_000;
const CACHE_MAX_ENTRIES = 1000;

export const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Mcp-Protocol-Version',
'Access-Control-Expose-Headers': 'WWW-Authenticate',
'Access-Control-Max-Age': '86400',
} as const;

export const METADATA_CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Mcp-Protocol-Version',
'Access-Control-Max-Age': '86400',
} as const;

const WELL_KNOWN = '/.well-known/oauth-protected-resource';

/** Path suffix of the public MCP URL ("/mcp"), empty when it has no path. */
function resourcePathSuffix(mcpPublicUrl: string): string {
const pathname = new URL(mcpPublicUrl).pathname.replace(/\/+$/, '');
return pathname === '/' ? '' : pathname;
}

/** Paths that serve the Protected Resource Metadata (RFC 9728), empty if OAuth is disabled. */
export function metadataPaths(config: Config): string[] {
if (!config.mcpPublicUrl) return [];
const suffix = resourcePathSuffix(config.mcpPublicUrl);
return suffix ? [WELL_KNOWN, WELL_KNOWN + suffix] : [WELL_KNOWN];
}

export function protectedResourceMetadata(config: Config): Record<string, unknown> {
return {
resource: config.mcpPublicUrl,
authorization_servers: [config.authServerUrl],
bearer_methods_supported: ['header'],
scopes_supported: ['mcp'],
resource_name: 'GitOps',
};
}

/** `WWW-Authenticate` challenge, with the metadata pointer when OAuth discovery is enabled. */
export function wwwAuthenticate(config: Config): string {
const base = 'Bearer realm="gitops-mcp"';
if (!config.mcpPublicUrl) return base;
const origin = new URL(config.mcpPublicUrl).origin;
const suffix = resourcePathSuffix(config.mcpPublicUrl);
return `${base}, resource_metadata="${origin}${WELL_KNOWN}${suffix}"`;
}

export type TokenCheck =
{ ok: true } | { ok: false; status: 401 | 429 | 503; message: string; retryAfter?: number };

/**
* Validates the caller's token against `GET /api/whoami`, so an expired or revoked token fails
* with HTTP 401 (and OAuth clients know they must refresh). Only successes are cached, keyed by
* the sha256 of the Authorization value: neither the token nor its hash is ever logged.
*/
export class TokenValidator {
private readonly cache = new Map<string, number>();

constructor(
private readonly now: () => number = Date.now,
private readonly ttlMs = CACHE_TTL_MS,
private readonly maxEntries = CACHE_MAX_ENTRIES,
) {}

async validate(authorization: string, client: GitOpsApiClient): Promise<TokenCheck> {
const key = createHash('sha256').update(authorization).digest('hex');
const expires = this.cache.get(key);
if (expires !== undefined) {
if (expires > this.now()) return { ok: true };
this.cache.delete(key);
}
try {
await client.get(WHOAMI_PATH);
} catch (err) {
if (err instanceof GitOpsApiError) {
if (err.status === 401 || err.status === 403) {
return {
ok: false,
status: 401,
message: 'Unauthorized: invalid, expired or revoked token (GitOps MCP key or OAuth).',
};
}
if (err.status === 429) {
return {
ok: false,
status: 429,
message: 'Too many requests to the GitOps API. Retry shortly.',
...(err.retryAfter !== undefined ? { retryAfter: err.retryAfter } : {}),
};
}
}
return {
ok: false,
status: 503,
message: 'GitOps API is temporarily unavailable. Try again in a moment.',
};
}
if (this.cache.size >= this.maxEntries) {
const oldest = this.cache.keys().next().value;
if (oldest !== undefined) this.cache.delete(oldest);
}
this.cache.set(key, this.now() + this.ttlMs);
return { ok: true };
}
}

export function sendNoContent(res: ServerResponse, headers: Record<string, string>): void {
if (res.headersSent) return;
res.writeHead(204, headers);
res.end();
}
25 changes: 24 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export interface Config {
port: number;
apiUrl: string;
apiTimeoutMs: number;
/** Public URL of the MCP endpoint (OAuth discovery). Undefined = OAuth discovery disabled. */
mcpPublicUrl?: string;
/** Issuer of the OAuth Authorization Server (GitOps). */
authServerUrl: string;
logLevel: LogLevel;
}

Expand All @@ -16,6 +20,21 @@ function positiveInt(name: string, raw: string | undefined, fallback: number): n
return n;
}

function optionalUrl(name: string, raw: string | undefined): string | undefined {
const value = raw?.trim();
if (!value) return undefined;
let parsed: URL;
try {
parsed = new URL(value);
} catch {
throw new Error(`${name} must be a valid URL`);
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error(`${name} must be an http(s) URL`);
}
return value.replace(/\/+$/, '');
}

export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
const apiUrl = env.GITOPS_API_URL?.trim();
if (!apiUrl) throw new Error('GITOPS_API_URL is required');
Expand All @@ -28,10 +47,14 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
if (!LOG_LEVELS.includes(level)) {
throw new Error(`LOG_LEVEL must be one of ${LOG_LEVELS.join(', ')}`);
}
const cleanApiUrl = apiUrl.replace(/\/+$/, '');
const mcpPublicUrl = optionalUrl('MCP_PUBLIC_URL', env.MCP_PUBLIC_URL);
return {
port: positiveInt('PORT', env.PORT, 3000),
apiUrl: apiUrl.replace(/\/+$/, ''),
apiUrl: cleanApiUrl,
apiTimeoutMs: positiveInt('GITOPS_API_TIMEOUT_MS', env.GITOPS_API_TIMEOUT_MS, 10000),
...(mcpPublicUrl ? { mcpPublicUrl } : {}),
authServerUrl: optionalUrl('GITOPS_AUTH_SERVER_URL', env.GITOPS_AUTH_SERVER_URL) ?? cleanApiUrl,
logLevel: level,
};
}
54 changes: 45 additions & 9 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ import { randomUUID } from 'node:crypto';
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { GitOpsApiClient } from './api/client.js';
import {
CORS_HEADERS,
METADATA_CORS_HEADERS,
TokenValidator,
metadataPaths,
protectedResourceMetadata,
sendNoContent,
wwwAuthenticate,
} from './auth.js';
import type { Config } from './config.js';
import type { Logger } from './log.js';
import { createMcpServer } from './server.js';
Expand Down Expand Up @@ -41,7 +50,12 @@ async function readJson(req: IncomingMessage): Promise<unknown> {
}

export function createHttpServer(config: Config, log: Logger): Server {
const validator = new TokenValidator();
const resourceMetadataPaths = metadataPaths(config);

async function handleMcp(req: IncomingMessage, res: ServerResponse, requestId: string) {
for (const [name, value] of Object.entries(CORS_HEADERS)) res.setHeader(name, value);
if (req.method === 'OPTIONS') return sendNoContent(res, {});
if (req.method !== 'POST') {
return sendJson(res, 405, rpcError(-32000, 'Method not allowed.'), { Allow: 'POST' });
}
Expand All @@ -51,11 +65,31 @@ export function createHttpServer(config: Config, log: Logger): Server {
return sendJson(
res,
401,
rpcError(-32001, 'Unauthorized: send "Authorization: Bearer <GitOps MCP key>".'),
{ 'WWW-Authenticate': 'Bearer realm="gitops-mcp"' },
rpcError(
-32001,
'Unauthorized: send "Authorization: Bearer <GitOps MCP key>" or connect through OAuth.',
),
{ 'WWW-Authenticate': wwwAuthenticate(config) },
);
}

const client = new GitOpsApiClient({
baseUrl: config.apiUrl,
authorization,
timeoutMs: config.apiTimeoutMs,
onCall: ({ path, status, durationMs }) =>
log.debug('api call', { requestId, apiPath: path, apiStatus: status, durationMs }),
});

const check = await validator.validate(authorization, client);
if (!check.ok) {
const headers: Record<string, string> = {};
if (check.status === 401) headers['WWW-Authenticate'] = wwwAuthenticate(config);
if (check.retryAfter !== undefined) headers['Retry-After'] = String(check.retryAfter);
const code = check.status === 401 ? -32001 : check.status === 429 ? -32029 : -32003;
return sendJson(res, check.status, rpcError(code, check.message), headers);
}

let body: unknown;
try {
body = await readJson(req);
Expand All @@ -65,13 +99,6 @@ export function createHttpServer(config: Config, log: Logger): Server {
: sendJson(res, 400, rpcError(-32700, 'Parse error: invalid JSON.'));
}

const client = new GitOpsApiClient({
baseUrl: config.apiUrl,
authorization,
timeoutMs: config.apiTimeoutMs,
onCall: ({ path, status, durationMs }) =>
log.debug('api call', { requestId, apiPath: path, apiStatus: status, durationMs }),
});
const server = createMcpServer({ client, log, requestId });
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
Expand Down Expand Up @@ -104,6 +131,15 @@ export function createHttpServer(config: Config, log: Logger): Server {
if (path === '/healthz' && (req.method === 'GET' || req.method === 'HEAD')) {
return sendJson(res, 200, { ok: true });
}
if (resourceMetadataPaths.includes(path)) {
if (req.method === 'OPTIONS') return sendNoContent(res, METADATA_CORS_HEADERS);
if (req.method === 'GET' || req.method === 'HEAD') {
return sendJson(res, 200, protectedResourceMetadata(config), {
...METADATA_CORS_HEADERS,
'Cache-Control': 'public, max-age=300',
});
}
}
if (path === '/mcp') return handleMcp(req, res, requestId);
sendJson(res, 404, { error: 'Not found' });
};
Expand Down
7 changes: 7 additions & 0 deletions test/fake-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,13 @@ const monitorSummary = (m: FakeDb['monitors'][number]) => ({

export function defaultRoutes(): Route[] {
return [
{
method: 'GET',
pattern: /^\/api\/whoami$/,
handler: () => ({
body: { type: 'mcp', audience: 'mcp', name: 'Test key', oauth: false },
}),
},
{
method: 'GET',
pattern: /^\/api\/projects$/,
Expand Down
1 change: 1 addition & 0 deletions test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export async function startMcp(api: FakeApi, overrides: Partial<Config> = {}): P
const config: Config = {
port: 0,
apiUrl: api.url,
authServerUrl: api.url,
apiTimeoutMs: 5000,
logLevel: 'debug',
...overrides,
Expand Down
11 changes: 5 additions & 6 deletions test/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,11 @@ describe('e2e with the MCP SDK client', () => {
await client.close();
});

it('a revoked token gives a readable tool error', async () => {
const client = await connect('gvs_revoked');
const result = await client.callTool({ name: 'list_projects', arguments: {} });
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0]!.text).toMatch(/token inválido o revocado/i);
await client.close();
it('a revoked token is rejected with HTTP 401, not a tool error', async () => {
const res = await post({ Authorization: 'Bearer gvs_revoked' });
expect(res.status).toBe(401);
expect(res.headers.get('www-authenticate')).toContain('Bearer realm="gitops-mcp"');
await expect(connect('gvs_revoked')).rejects.toThrow();
});

it('never logs the token', () => {
Expand Down
Loading
Loading