Aplica las políticas de acceso de la organización durante la recuperación de RAG para evitar que los modelos de IA accedan a datos sensibles no autorizados.
También conocido como fortisil/gateco-sdk-python, gateco-sdk-python
- Stars
- 0
- Herramientas
- 7
- Descargas, 30 días
- 623
- Última versión
- 1.13.0
- Último commit
- 7 oct 2026
- Licencia
- MIT
¿Qué es Gateco MCP?
Gateco es un MCP server. Aplica las políticas de acceso de la organización durante la recuperación de RAG para evitar que los modelos de IA accedan a datos sensibles no autorizados. Expone 7 herramientas, como gateco_retrieve, gateco_ask, gateco_check_access.
Resumen generado a partir del README del proyecto
Acerca del MCP server de Gateco
Gateco proporciona una capa de recuperación consciente de los permisos diseñada para situarse entre los agentes de IA y los vector stores. Evita la exposición de datos no autorizados evaluando las políticas de acceso de la organización antes de que cualquier contenido llegue a un modelo de lenguaje extenso. Esto garantiza que la información sensible, como documentos de RR. HH. o salarios ejecutivos, permanezca oculta para los usuarios que no cuentan con el acceso de clasificación necesario.
Los desarrolladores pueden integrar este servicio utilizando el SDK de Python a través de clientes síncronos o asíncronos. El sistema admite varios métodos de autenticación, incluyendo API keys que comienzan con el prefijo gck_ o inicios de sesión con email y contraseña que emiten JWT de corta duración. Para el desarrollo local y clientes compatibles con MCP como Claude Desktop o Cursor, los usuarios pueden instalar el paquete gateco[mcp] y configurar la variable de entorno GATECO_API_KEY.
El servidor ofrece múltiples modos de búsqueda, incluyendo vector, keyword, hybrid y grep. También cuenta con Control de Acceso Basado en Relaciones (REBAC) para gestionar permisos complejos mediante relaciones directas. Al utilizar herramientas como el simulador de acceso o la síntesis de respuestas fundamentadas, los equipos pueden verificar que sus pipelines de RAG respetan límites de seguridad estrictos.
Qué puedes hacer con él
- 1Prevenir filtraciones de datos sensiblesGarantiza que un asistente de IA no revele información restringida, como salarios, a empleados no autorizados durante una tarea de recuperación.
- 2Ejecutar búsquedas con control de permisosRealiza búsquedas hybrid o keyword que redactan automáticamente los fragmentos basándose en los derechos de acceso del principal.
Escrito a partir del README del proyecto. Cada caso de uso se verifica con una cita del mismo.
Cómo instalar Gateco MCP
Formatos verificados el 10 nov 2026Instalar Gateco MCP en Claude Code
$ claude mcp add --env GATECO_API_KEY=<YOUR_GATECO_API_KEY> gateco-sdk-python -- uvx gatecoInstalar Gateco MCP en Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"gateco-sdk-python": {
"command": "uvx",
"args": [
"gateco"
],
"env": {
"GATECO_API_KEY": "<YOUR_GATECO_API_KEY>"
}
}
}
}Instalar Gateco MCP en VS Code
.vscode/mcp.json
{
"servers": {
"gateco-sdk-python": {
"type": "stdio",
"command": "uvx",
"args": [
"gateco"
],
"env": {
"GATECO_API_KEY": "<YOUR_GATECO_API_KEY>"
}
}
}
}Instalar Gateco MCP en Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"gateco-sdk-python": {
"command": "uvx",
"args": [
"gateco"
],
"env": {
"GATECO_API_KEY": "<YOUR_GATECO_API_KEY>"
}
}
}
}Instalar Gateco MCP en Codex
~/.codex/config.toml
[mcp_servers.gateco-sdk-python] command = "uvx" args = ["gateco"] [mcp_servers.gateco-sdk-python.env] GATECO_API_KEY = "<YOUR_GATECO_API_KEY>"
Instalar Gateco MCP en Gemini CLI
~/.gemini/settings.json
{
"mcpServers": {
"gateco-sdk-python": {
"command": "uvx",
"args": [
"gateco"
],
"env": {
"GATECO_API_KEY": "<YOUR_GATECO_API_KEY>"
}
}
}
}Herramientas de Gateco MCP 7
Detectado desde el READMEgateco_retrievegateco_askgateco_check_accessgateco_list_connectorsgateco_list_principalsgateco_list_groupsgateco_resolve_principal
| gateco_retrieve | — | |
| gateco_ask | — | |
| gateco_check_access | — | |
| gateco_list_connectors | — | |
| gateco_list_principals | — | |
| gateco_list_groups | — | |
| gateco_resolve_principal | — |
Configuración
GATECO_API_KEYObligatorioSecretoGateco API key WITH THE retrieve SCOPE (Settings > API Keys > Create, tick retrieve). Every plan. Six of seven tools run on it; gateco_check_access needs `gateco login`.
GATECO_BASE_URLGateco API base URL. Defaults to https://api.gateco.ai; set only for self-hosted or staging deployments.
| Nombre | Descripción | Tipo |
|---|---|---|
| GATECO_API_KEY | Gateco API key WITH THE retrieve SCOPE (Settings > API Keys > Create, tick retrieve). Every plan. Six of seven tools run on it; gateco_check_access needs `gateco login`. | ObligatorioSecreto |
| GATECO_BASE_URL | Gateco API base URL. Defaults to https://api.gateco.ai; set only for self-hosted or staging deployments. |
Verificaciones automáticas
Ejecutado 13 nov 2026Informe completo →Pasó nuestras verificaciones automáticas. Esto no es una auditoría de seguridad: lee el código y dale al servidor el acceso más limitado que necesite. Cómo funcionan las verificaciones
- Repositorio de origen vinculado y accesibleAprobado
- Licencia de código abierto (OSI)Aprobado
- Commit o lanzamiento en el último añoAprobado
- El nombre del paquete no es similar a un paquete popularAprobado
- El endpoint remoto usa HTTPSNo verificado
- Las herramientas destructivas están etiquetadasAprobado
- Sin instrucciones ocultas para el modeloAprobado
- Sin avisos críticos en el paquete ni en sus dependenciasAprobado
README
Ver en GitHubGateco Python SDK
Official Python client for the Gateco API — permission-aware retrieval for AI systems.
The problem it solves
Without Gateco, when an employee asks your AI assistant "What is the CEO's salary?", the RAG pipeline returns the salary from a leaked HR document.
With Gateco:
from gateco_sdk import GatecoClient
client = GatecoClient("https://api.gateco.ai")
client.login("you@yourco.com", "...")
result = client.retrievals.execute(
query="What is the CEO's salary?",
principal_id="user_james_wu",
connector_id="connector_hr_docs",
search_mode="hybrid",
)
# result.allowed_chunks → [] (denied — James Wu lacks HR classification access)
# result.denied_count → 1
# result.decision → "DENIED"
# Your AI model never sees the salary data
Gateco sits between your AI agent and your vector store. Every retrieval is evaluated against your access policies before any content reaches the model.
Installation
pip install gateco
For MCP server support (Claude Desktop, Cursor, etc.):
pip install gateco[mcp]
Authentication
Gateco API keys use the format gck_<env>_<random> (e.g. gck_live_abc123...).
Generate keys via the dashboard or via client.api_keys.create(name="my-service").
from gateco_sdk import AsyncGatecoClient, GatecoClient
# Async client with API key
client = AsyncGatecoClient("https://api.gateco.ai", api_key="gck_live_abc123...")
# Sync client with API key
client = GatecoClient("https://api.gateco.ai", api_key="gck_live_abc123...")
# Or use email/password login (issues a short-lived JWT)
client = GatecoClient("https://api.gateco.ai")
client.login("user@example.com", "password")
The API key is sent as the X-API-Key header on every request. Set it via the
GATECO_API_KEY environment variable when using the CLI or MCP server. The key takes
precedence over a stored login.
No credential at all? Since 1.13.0 a client constructed with no api_key, no
GATECO_API_KEY and no access_token reads the session that gateco login stored in
~/.gateco/credentials.json (and its base_url), and writes refreshed tokens back. One
login on a machine serves the CLI, the MCP server and your own scripts; do not copy the
file between machines, because refresh rotates and the two copies would revoke each other.
Which routes accept an API key
A key carries explicit scopes, chosen when it is created (Settings > API Keys, every plan).
Everything not listed here needs a user session (gateco login or client.login(...));
a key sent there gets 401 AUTH_JWT_REQUIRED, and a key without the needed scope gets
403 API_KEY_SCOPE_MISSING.
| Scope | Routes |
|---|---|
retrieve |
POST /api/retrievals/execute, POST /api/retrievals/filter, POST /api/answers/execute, GET /api/principals, GET /api/principals/:id, POST /api/principals/resolve, GET /api/groups (since 2026-10-02), GET /api/connectors (id, name, type, status) |
ingest |
POST /api/v1/ingest, /batch, /file, /files, DELETE /api/v1/resources/:id, /api/v1/ingest/jobs* |
relationships |
POST, GET, DELETE /api/relationships |
principals |
POST, PATCH, DELETE /api/principals (local directory) |
| any key | GET /api/users/me (reports the key's name and scopes) |
Session only: policies, connector create/update/delete and their search and ingestion configs, identity providers, API-key management, audit, retrieval history, billing, the access simulator, classification suggestions.
Quick Start
Async (recommended for production services)
import asyncio
from gateco_sdk import AsyncGatecoClient
async def main():
async with AsyncGatecoClient(
"https://api.gateco.ai",
api_key="gck_live_abc123...",
) as client:
# Policy-gated retrieval — the core Gateco primitive
result = await client.retrievals.execute(
query="What is the CEO's salary?",
principal_id="user_james_wu",
connector_id="connector_hr_docs",
search_mode="hybrid",
alpha=0.7, # 70% vector weight, 30% keyword
top_k=5,
)
# Allowed chunks are safe to pass to your LLM
for chunk in result.allowed_chunks:
print(f"[ALLOWED] {chunk.resource_id} score={chunk.score}")
# Denied chunks are redacted — only metadata is surfaced
print(f"Denied: {result.denied_count} chunk(s)")
asyncio.run(main())
Synchronous (scripts and notebooks)
from gateco_sdk import GatecoClient
with GatecoClient("https://api.gateco.ai", api_key="gck_live_abc123...") as client:
result = client.retrievals.execute(
query="What is the CEO's salary?",
principal_id="user_james_wu",
connector_id="connector_hr_docs",
search_mode="hybrid",
)
print(result.decision) # "DENIED"
Available Namespaces
Every namespace, and every method on it, is available on both AsyncGatecoClient (async) and GatecoClient (sync); tests/test_sync_parity.py fails the build if the two drift.
| Namespace | Description |
|---|---|
client.answers |
Grounded answer synthesis with policy-filtered citations (Team+) |
client.api_keys |
Create, list, delete, and rotate API keys |
client.audit |
Audit log listing and CSV export |
client.auth |
Login, signup, token refresh, logout |
client.billing |
Plans, usage meters, invoices, subscription, Stripe checkout and portal |
client.connectors |
Connector CRUD, connection testing, search/ingestion config, coverage, classification suggestions |
client.dashboard |
Aggregated dashboard statistics with optional sparklines |
client.data_catalog |
Gated resource listing and metadata updates |
client.groups |
Read-only groups directory with live member counts |
client.identity_providers |
Identity provider CRUD and sync (Okta, Azure Entra ID, AWS IAM, GCP) |
client.ingest |
Single-document, batch, and file ingestion (Tier 1 connectors) |
client.onboarding |
Onboarding status (6 computed steps) and checklist dismissal |
client.pipelines |
Pipeline CRUD and run management |
client.policies |
Policy CRUD, lifecycle (activate/archive), and templates |
client.principals |
Principal listing, detail, and resolution by email or provider subject |
client.relationships |
REBAC direct-relation CRUD — create, list, delete 1-hop tuples (Team+) |
client.retroactive |
Retroactive vector registration for existing connectors |
client.retrievals |
Permission-gated retrieval execution, policy filter, and history |
client.simulator |
Dry-run, live-preview, and batch-preview access simulation (Growth+) |
client.sources |
Content-source connections (Drive, SharePoint, Confluence, Notion): create, test, ACL coverage |
client.users |
Current user profile — get_me(), update_me(name) |
Retrieval Search Modes
# Vector search (default) — semantic similarity
result = await client.retrievals.execute(
query="quarterly earnings", principal_id="...", connector_id="...",
)
# Keyword search — ranked full-text search (BM25)
result = await client.retrievals.execute(
query="quarterly earnings", principal_id="...", connector_id="...",
search_mode="keyword",
)
# Hybrid search — vector + keyword fused (RRF)
result = await client.retrievals.execute(
query="quarterly earnings", principal_id="...", connector_id="...",
search_mode="hybrid",
alpha=0.5, # 1.0 = all-vector, 0.0 = all-keyword
)
# Grep — exact pattern matching
result = await client.retrievals.execute(
query="ERR-4021", principal_id="...", connector_id="...",
search_mode="grep",
pattern_type="regex",
case_sensitive=False,
)
API Key Management
# Create a key — the plaintext is returned exactly once
key_info = await client.api_keys.create(name="prod-worker")
print(key_info["key"]) # gck_live_abc123... (store this securely)
print(key_info["prefix"]) # gck_live_abc
# List keys (plaintext never returned after creation)
keys = await client.api_keys.list()
# Rotate a key — old key is invalidated immediately
new_key = await client.api_keys.rotate(key_id="key-uuid-here")
# Delete a key
await client.api_keys.delete(key_id="key-uuid-here")
Relationship-Based Access Control (REBAC)
# Create a direct relation: Alice owns resource R
rel = await client.relationships.create(
subject_principal_id="principal-uuid",
relation_name="owner_of",
object_resource_id="resource-uuid",
)
print(rel["id"])
# List relations for a principal
rels = await client.relationships.list(
subject_id="principal-uuid",
relation="owner_of",
)
# Delete a relation (invalidates policy cache immediately)
await client.relationships.delete(relationship_id=rel["id"])
Use relation.<name> as a policy condition field to gate access on the existence of a tuple:
# Policy rule: allow access when principal has owner_of relation on the resource
rule = {"field": "relation.owner_of", "operator": "eq", "value": True}
Onboarding Status
# Check which onboarding steps are complete
status = await client.onboarding.status()
for step in status["steps"]:
print(f"{step['name']:30s} {step['status']}")
# Dismiss the checklist once the org is fully configured
await client.onboarding.dismiss()
Principal Resolution
# Resolve a principal by email (read-only — never creates)
principal = await client.principals.resolve(email="alice@company.com")
# Resolve by raw IDP-side user ID
principal = await client.principals.resolve(provider_subject="okta-user-123")
# Scoped to a specific identity provider
principal = await client.principals.resolve(
email="alice@company.com",
identity_provider_id="idp-uuid-here",
)
Grounded Answer Synthesis (Team+)
answer = await client.answers.execute(
query="Summarise the Q4 revenue results.",
principal_id="user_alice",
connector_id="connector_finance_docs",
search_mode="hybrid",
)
print(answer.answer_text) # LLM-generated answer from allowed chunks only
print(answer.outcome) # "answered" | "no_access" | "insufficient_context"
for citation in answer.citations:
print(f" [{citation.score:.2f}] {citation.resource_id}")
Policy Creation
# Create an RBAC policy
policy = await client.policies.create(
name="Engineering read-only",
description="Allow engineering group to read internal resources",
type="rbac",
effect="allow",
rules=[{
"description": "Engineering group members",
"effect": "allow",
"conditions": [{"field": "principal.groups", "operator": "contains", "value": "engineering"}],
"priority": 1,
}],
resource_selectors=[{"field": "resource.classification", "op": "lte", "value": "internal"}],
)
Policy validation rules:
- Condition fields must use
resource.,principal., orrelation.prefix. Bare field names (e.g.,"classification") are rejected with 422 — they silently resolve against the principal rather than the resource. - Policies with empty
resource_selectorsrequireapply_to_all_resources=Truein the request body to opt into matching all resources explicitly.
Retrieval Diagnostics
result = await client.retrievals.execute(
query="quarterly earnings",
principal_id="user_alice",
connector_id="connector_finance_docs",
search_mode="hybrid",
)
# All retrieval responses include diagnostics
print(result.diagnostics.outcome_detail) # Human-readable explanation
print(result.diagnostics.candidates_fetched) # How many candidates were checked
print(result.diagnostics.candidates_denied) # How many were denied by policy
print(result.diagnostics.refill_rounds) # How many refill rounds ran (0 = first pass sufficient)
Connector Preflight Check
# Check if a connector is production-ready before using it in retrievals
preflight = client.connectors.preflight(connector_id="...")
print(preflight.ready_for_production) # bool
print(preflight.recommendation) # What to fix next
for check in preflight.checks:
print(f"{check.name}: {'PASS' if check.passed else 'FAIL'} (blocking={check.blocking})")
Dashboard Activation Metrics
# Aggregated dashboard statistics
stats = await client.dashboard.stats()
print(stats["total_retrievals"])
print(stats["allowed_retrievals"])
# Activation funnel metrics
activation = client.dashboard.get_activation_stats()
print(activation.total_retrievals_30d)
print(activation.allowed_retrievals_30d)
print(activation.no_access_retrievals_30d) # Retrievals where 0 results were authorized
print(activation.p95_latency_ms) # End-to-end p95 latency
Pagination
List endpoints return a Page object. Use list_all() for automatic async pagination:
async for connector in client.connectors.list_all():
print(connector.name)
Rate Limits
Three endpoints enforce per-org-per-minute limits:
| Endpoint | Limit |
|---|---|
POST /api/retrievals/execute |
60/min |
POST /api/answers/execute |
20/min |
POST /api/simulator/preview |
10/min |
Exceeded limits raise RateLimitError. The SDK retries automatically with exponential backoff (configurable via max_retries). Limits are org-scoped and reset on process restart (in-memory implementation).
Error Handling
from gateco_sdk.errors import NotFoundError, RateLimitError, AuthenticationError
try:
conn = await client.connectors.get("nonexistent-id")
except NotFoundError:
print("Connector not found")
except RateLimitError as e:
print(f"Rate limited — retry after {e.retry_after}s")
except AuthenticationError:
print("Invalid or expired credentials")
CLI
The gateco command is installed with the SDK and uses the same credentials.
# Log in once; you are prompted for the password (or pipe it on stdin).
# Passing --password on the command line works but lands in shell history.
gateco login --email admin@company.com
gateco whoami # base URL, credential in use, key scopes
# Connectors: inspect and configure (user session only)
gateco connectors list
gateco connectors get <connector_id>
gateco connectors get-search-config <connector_id>
gateco connectors set-search-config <connector_id> --json '{"table_name": "docs", "vector_column": "embedding", "content_column": "text"}'
gateco connectors get-ingestion-config <connector_id>
gateco connectors set-ingestion-config <connector_id> --file ingestion.json
# Ingest: .txt/.md are sent as text; PDF, Word, PowerPoint, Excel and CSV are uploaded
gateco ingest report.txt --connector-id <id> --classification confidential --sensitivity high
gateco ingest "Q3 board deck.pdf" --connector-id <id> --classification confidential --sensitivity high --domain finance
gateco ingest-batch ./documents --connector-id <id> --glob "*.md"
# Retrieve as a principal (API key with the retrieve scope, or a session)
gateco retrieve --connector-id <id> --principal-id <id> --query "revenue report" --search-mode hybrid
--classification accepts public, internal, confidential, restricted;
--sensitivity accepts low, medium, high, critical (gateco ingest --help lists them).
MCP Server (Model Context Protocol)
The optional MCP server lets AI agents (Claude Desktop, Cursor, etc.) perform permission-aware retrieval without any custom code.
pip install gateco[mcp]
# Start the server
gateco mcp serve
# Or use the direct entry point (for MCP host configs)
gateco-mcp
Claude Desktop Configuration
{
"mcpServers": {
"gateco": {
"command": "gateco-mcp",
"env": {
"GATECO_API_KEY": "gck_live_abc123...",
"GATECO_BASE_URL": "https://api.gateco.ai"
}
}
}
}
Available MCP Tools
| Tool | Description |
|---|---|
gateco_retrieve |
Permission-aware retrieval (vector/keyword/hybrid/grep) |
gateco_ask |
Grounded answer synthesis with search modes (Team+) |
gateco_check_access |
Dry-run access simulation (Growth+). User session only (gateco login); not callable with an API key |
gateco_list_connectors |
List connectors with readiness levels |
gateco_list_principals |
List identity principals |
gateco_list_groups |
List groups (IdP-synced and local directory) with live member counts. Works with a retrieve-scoped key against a backend from 2026-10-02 on; older backends answer that a user session is needed |
gateco_resolve_principal |
Resolve a principal by email or provider subject |
All tools return markdown-formatted text. Denied content is never exposed — only denial reasons and counts are shown.
Development
pip install -e ".[dev]"
pytest -v
# Run MCP server tests
pytest tests/test_mcp/ -v
# With coverage
pytest --cov=src/gateco_sdk
Links
Preguntas sobre Gateco MCP
¿Cómo agrego Gateco MCP a Claude Code?
Ejecuta claude mcp add --env GATECO_API_KEY=<YOUR_GATECO_API_KEY> gateco-sdk-python -- uvx gateco en tu terminal. Añade --scope user para que esté disponible en todos los proyectos.
¿Cómo agrego Gateco MCP a Cursor?
Abre ~/.cursor/mcp.json y añade el servidor en mcpServers, usando la configuración de Cursor que se muestra en la sección de instalación de arriba.
¿Qué herramientas proporciona Gateco MCP?
Expone 7 herramientas, incluidas gateco_retrieve, gateco_ask, gateco_check_access, gateco_list_connectors, gateco_list_principals.
¿Cómo evita Gateco las filtraciones de datos en los pipelines de RAG?
Gateco se sitúa entre tu agente de IA y tu vector store, evaluando cada recuperación frente a las políticas de acceso antes de que el contenido llegue al modelo.
¿Puedo usar Gateco con vector stores existentes?
Sí, Gateco actúa como una capa de recuperación consciente de los permisos, compatible con varios modos de búsqueda como vector, keyword, hybrid y grep.