* feat: add TenantExtension auth to MCP endpoint Replace static MCP_AUTH_TOKEN check with TenantExtension authentication, making MCP use the same auth path as REST API. - MCPMiddleware now calls tenant_extension.authenticate() - Sets _current_schema from TenantContext for multi-tenant isolation - Returns 401 on AuthenticationError (same as REST API) - DefaultTenantExtension: no auth (local dev) - ApiKeyTenantExtension: validates against env var - CloudTenantExtension: HMAC + DB lookup (production) Adds tests for middleware auth rejection, acceptance, and schema routing. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Address PR review: backwards compatibility for MCP auth - Keep MCP_AUTH_TOKEN env var for legacy MCP servers - Add authenticate_mcp() method to TenantExtension base class - Default implementation calls authenticate() - Extensions can override to opt-out of MCP auth - Add mcp_auth_disabled config option to ApiKeyTenantExtension - Set HINDSIGHT_API_TENANT_MCP_AUTH_DISABLED=true to skip MCP auth - Remove CloudTenantExtension from public docstring - Add tests for legacy auth token and mcp_auth_disabled flag - Update MCP docs with new auth configuration Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add search_docs MCP tool for documentation search Implements a new MCP tool that searches Hindsight documentation using Vectorize RAG pipelines. The tool supports: - Searching core (OSS) docs, cloud docs, or both - Configurable number of results (1-10) - Returns ranked results with URLs, similarity scores, and text snippets New environment variables: - HINDSIGHT_API_VECTORIZE_ORG_ID - HINDSIGHT_API_VECTORIZE_API_TOKEN - HINDSIGHT_API_VECTORIZE_CORE_PIPELINE_ID - HINDSIGHT_API_VECTORIZE_CLOUD_PIPELINE_ID - HINDSIGHT_API_VECTORIZE_API_BASE_URL Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add documentation for search_docs MCP tool - Add Vectorize environment variables to configuration.md - Add search_docs tool to MCP server available tools - Add reflect tool documentation (was missing) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add tests for search_docs MCP tool Tests cover: - DocsSource enum values and parsing - _clean_text HTML stripping helper - _search_vectorize_pipeline with mocked httpx - Tool registration and function execution - Source filtering (core/cloud/all) - Result sorting by similarity - Error handling for pipeline failures - HTML cleaning in results - Invalid source defaulting to 'all' Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Move search_docs to hindsight-cloud, add MCPExtension pattern - Add MCPExtension base class for registering additional MCP tools - Load MCPExtension in create_mcp_server when configured - Remove search_docs tool (moved to hindsight-cloud CloudMCPExtension) - Remove Vectorize config from hindsight-core - Add tests for MCPExtension pattern - Update docs to remove search_docs references The MCPExtension pattern allows cloud (or any extension package) to register additional MCP tools via: HINDSIGHT_API_MCP_EXTENSION=package.module:ExtensionClass Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Address PR review feedback - Remove CloudTenantExtension mention from MCPMiddleware docstring - Fix docs: clarify that ApiKeyTenantExtension must be explicitly enabled - Revert changes to versioned docs (0.3 and 0.4) - synced automatically on release Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Format mcp.py line length Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
108 lines
3.2 KiB
Python
108 lines
3.2 KiB
Python
"""Tenant Extension for multi-tenancy and API key authentication."""
|
|
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass
|
|
|
|
from hindsight_api.extensions.base import Extension
|
|
from hindsight_api.models import RequestContext
|
|
|
|
|
|
class AuthenticationError(Exception):
|
|
"""Raised when authentication fails."""
|
|
|
|
def __init__(self, reason: str):
|
|
self.reason = reason
|
|
super().__init__(f"Authentication failed: {reason}")
|
|
|
|
|
|
@dataclass
|
|
class TenantContext:
|
|
"""
|
|
Tenant context returned by authentication.
|
|
|
|
Contains the PostgreSQL schema name for tenant isolation.
|
|
All database queries will use fully-qualified table names
|
|
with this schema (e.g., schema_name.memory_units).
|
|
"""
|
|
|
|
schema_name: str
|
|
|
|
|
|
@dataclass
|
|
class Tenant:
|
|
"""
|
|
Represents a tenant for worker discovery.
|
|
|
|
Used by list_tenants() to return tenant information including
|
|
the PostgreSQL schema name for database operations.
|
|
"""
|
|
|
|
schema: str
|
|
|
|
|
|
class TenantExtension(Extension, ABC):
|
|
"""
|
|
Extension for multi-tenancy and API key authentication.
|
|
|
|
This extension validates incoming requests and returns the tenant context
|
|
including the PostgreSQL schema to use for database operations.
|
|
|
|
Built-in implementation:
|
|
hindsight_api.extensions.builtin.tenant.ApiKeyTenantExtension
|
|
|
|
Enable via environment variable:
|
|
HINDSIGHT_API_TENANT_EXTENSION=hindsight_api.extensions.builtin.tenant:ApiKeyTenantExtension
|
|
HINDSIGHT_API_TENANT_API_KEY=your-secret-key
|
|
|
|
The returned schema_name is used for fully-qualified table names in queries,
|
|
enabling tenant isolation at the database level.
|
|
"""
|
|
|
|
@abstractmethod
|
|
async def authenticate(self, context: RequestContext) -> TenantContext:
|
|
"""
|
|
Authenticate the action context and return tenant context.
|
|
|
|
Args:
|
|
context: The action context containing API key and other auth data.
|
|
|
|
Returns:
|
|
TenantContext with the schema_name for database operations.
|
|
|
|
Raises:
|
|
AuthenticationError: If authentication fails.
|
|
"""
|
|
...
|
|
|
|
@abstractmethod
|
|
async def list_tenants(self) -> list[Tenant]:
|
|
"""
|
|
List all tenants that should be processed by workers.
|
|
|
|
This method is used by the worker to discover all tenants that need
|
|
task polling. Workers will poll for pending tasks in each tenant's schema.
|
|
|
|
Returns:
|
|
List of Tenant objects containing schema information.
|
|
For single-tenant setups, return [Tenant(schema="public")].
|
|
"""
|
|
...
|
|
|
|
async def authenticate_mcp(self, context: RequestContext) -> TenantContext:
|
|
"""
|
|
Authenticate MCP requests.
|
|
|
|
By default, this calls authenticate(). Override this method to provide
|
|
different authentication behavior for MCP endpoints (e.g., to disable
|
|
auth for backwards compatibility with existing MCP servers).
|
|
|
|
Args:
|
|
context: The action context containing API key and other auth data.
|
|
|
|
Returns:
|
|
TenantContext with the schema_name for database operations.
|
|
|
|
Raises:
|
|
AuthenticationError: If authentication fails.
|
|
"""
|
|
return await self.authenticate(context)
|