tabella-enable 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """tabella-enable: AI-enablement generators (REST access layer, MCP tool manifest).
2
+
3
+ M2 adds the live MCP server and RAG vectorization (chunking, embeddings,
4
+ pgvector indexing) per descriptor vectorization profiles.
5
+ """
@@ -0,0 +1,94 @@
1
+ """Live MCP server over a Tabella catalog (stdio transport).
2
+
3
+ Tools are generated from the catalog exactly per the tool-manifest spec:
4
+ `query_<asset>` (equality filters + pagination) for every MCP-enabled asset,
5
+ plus `search_<asset>` (semantic search) for vectorized assets when a search
6
+ service is configured.
7
+
8
+ The tool listing and dispatch are pure functions (`catalog_tools`,
9
+ `call_catalog_tool`) so they are testable without an MCP client; the stdio
10
+ wiring in `run_stdio` is a thin shell over the official `mcp` SDK.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from typing import Any
17
+
18
+ from tabella_core.connectors import get_connector
19
+ from tabella_core.models import AssetDescriptor
20
+
21
+ from tabella_enable.tools import build_manifest
22
+
23
+ _RESERVED = {"limit", "offset"}
24
+
25
+
26
+ def catalog_tools(
27
+ catalog: list[AssetDescriptor], *, with_search: bool
28
+ ) -> list[dict[str, Any]]:
29
+ manifest = build_manifest(catalog)
30
+ tools = manifest["tools"]
31
+ if not with_search:
32
+ tools = [t for t in tools if not t["name"].startswith("search_")]
33
+ return tools
34
+
35
+
36
+ def call_catalog_tool(
37
+ catalog: list[AssetDescriptor],
38
+ name: str,
39
+ arguments: dict[str, Any],
40
+ *,
41
+ search=None,
42
+ ) -> dict[str, Any]:
43
+ by_tool = {t["name"]: t for t in catalog_tools(catalog, with_search=search is not None)}
44
+ if name not in by_tool:
45
+ raise KeyError(f"Unknown tool: {name}")
46
+ asset_id = by_tool[name]["asset"]
47
+ descriptor = next(d for d in catalog if d.id == asset_id)
48
+
49
+ if name.startswith("search_"):
50
+ results = search.search(
51
+ descriptor, arguments["query"], int(arguments.get("top_k", 5))
52
+ )
53
+ return {"data": results, "asset": asset_id}
54
+
55
+ limit = min(int(arguments.get("limit", 100)), descriptor.access.row_limit)
56
+ offset = int(arguments.get("offset", 0))
57
+ filters = {k: v for k, v in arguments.items() if k not in _RESERVED}
58
+ connector = get_connector(descriptor.source.connector)
59
+ records, total = connector.fetch(descriptor, filters=filters, limit=limit, offset=offset)
60
+ return {
61
+ "data": records,
62
+ "pagination": {"limit": limit, "offset": offset, "total": total},
63
+ "asset": asset_id,
64
+ }
65
+
66
+
67
+ async def run_stdio(catalog: list[AssetDescriptor], *, search=None) -> None:
68
+ import mcp.types as types
69
+ from mcp.server import Server
70
+ from mcp.server.stdio import stdio_server
71
+
72
+ server = Server("tabella")
73
+
74
+ @server.list_tools()
75
+ async def list_tools() -> list[types.Tool]:
76
+ return [
77
+ types.Tool(
78
+ name=t["name"],
79
+ description=t["description"],
80
+ inputSchema=t["input_schema"],
81
+ )
82
+ for t in catalog_tools(catalog, with_search=search is not None)
83
+ ]
84
+
85
+ @server.call_tool()
86
+ async def call_tool(name: str, arguments: dict[str, Any]) -> list[types.TextContent]:
87
+ try:
88
+ result = call_catalog_tool(catalog, name, arguments or {}, search=search)
89
+ except Exception as exc:
90
+ result = {"error": str(exc)}
91
+ return [types.TextContent(type="text", text=json.dumps(result, default=str))]
92
+
93
+ async with stdio_server() as (read, write):
94
+ await server.run(read, write, server.create_initialization_options())
@@ -0,0 +1,13 @@
1
+ """RAG vectorization and semantic search (spec/ai-artifact-manifest.md, part 2)."""
2
+
3
+ from tabella_enable.rag.embeddings import embedding_provider_from_env
4
+ from tabella_enable.rag.pipeline import vectorize_asset
5
+ from tabella_enable.rag.search import SearchService
6
+ from tabella_enable.rag.store import vector_store_from_env
7
+
8
+ __all__ = [
9
+ "SearchService",
10
+ "embedding_provider_from_env",
11
+ "vector_store_from_env",
12
+ "vectorize_asset",
13
+ ]
@@ -0,0 +1,46 @@
1
+ """Chunking strategies for RAG vectorization.
2
+
3
+ - `document`: one chunk per record — right for short records (tickets, rows).
4
+ - `fixed`: character windows with 10% overlap.
5
+ - `semantic`: sentence-boundary packing up to chunk_size (v0.1 approximation
6
+ of semantic chunking; embedding-based splitting is a later refinement).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ from tabella_core.models import ChunkingStrategy
14
+
15
+ _SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
16
+
17
+
18
+ def chunk_text(text: str, strategy: ChunkingStrategy, chunk_size: int) -> list[str]:
19
+ text = text.strip()
20
+ if not text:
21
+ return []
22
+ if strategy == ChunkingStrategy.document or len(text) <= chunk_size:
23
+ return [text]
24
+ if strategy == ChunkingStrategy.semantic:
25
+ return _pack_sentences(text, chunk_size)
26
+ return _fixed_windows(text, chunk_size)
27
+
28
+
29
+ def _fixed_windows(text: str, chunk_size: int) -> list[str]:
30
+ overlap = max(chunk_size // 10, 1)
31
+ step = chunk_size - overlap
32
+ return [text[start : start + chunk_size] for start in range(0, len(text), step)]
33
+
34
+
35
+ def _pack_sentences(text: str, chunk_size: int) -> list[str]:
36
+ chunks: list[str] = []
37
+ current = ""
38
+ for sentence in _SENTENCE_END.split(text):
39
+ if current and len(current) + len(sentence) + 1 > chunk_size:
40
+ chunks.append(current)
41
+ current = sentence
42
+ else:
43
+ current = f"{current} {sentence}".strip()
44
+ if current:
45
+ chunks.append(current)
46
+ return chunks
@@ -0,0 +1,85 @@
1
+ """Embedding providers.
2
+
3
+ - `hash` — deterministic, offline, dependency-free: token-hash bag-of-words
4
+ vectors. Not semantically meaningful, but stable and cheap; the dev/test
5
+ default so the whole RAG path runs with no API key or model server.
6
+ - `openai` — any OpenAI-compatible /v1/embeddings endpoint (OpenAI, LiteLLM,
7
+ Ollama, vLLM...). Configure via TABELLA_EMBED_* env vars.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import math
14
+ import os
15
+ import re
16
+
17
+ from tabella_core.interfaces import EmbeddingProvider
18
+
19
+ _TOKEN = re.compile(r"[a-z0-9]+")
20
+
21
+
22
+ class HashEmbeddings(EmbeddingProvider):
23
+ name = "hash"
24
+
25
+ def __init__(self, dimensions: int = 256):
26
+ self.dimensions = dimensions
27
+ self.model = f"tabella-hash-{dimensions}"
28
+
29
+ def embed(self, texts: list[str]) -> list[list[float]]:
30
+ return [self._embed_one(t) for t in texts]
31
+
32
+ def _embed_one(self, text: str) -> list[float]:
33
+ vector = [0.0] * self.dimensions
34
+ for token in _TOKEN.findall(text.lower()):
35
+ digest = hashlib.sha256(token.encode()).digest()
36
+ index = int.from_bytes(digest[:4], "big") % self.dimensions
37
+ sign = 1.0 if digest[4] % 2 == 0 else -1.0
38
+ vector[index] += sign
39
+ norm = math.sqrt(sum(v * v for v in vector)) or 1.0
40
+ return [v / norm for v in vector]
41
+
42
+
43
+ class OpenAICompatibleEmbeddings(EmbeddingProvider):
44
+ name = "openai"
45
+
46
+ def __init__(
47
+ self,
48
+ api_url: str | None = None,
49
+ api_key: str | None = None,
50
+ model: str | None = None,
51
+ ):
52
+ self.api_url = (
53
+ api_url or os.environ.get("TABELLA_EMBED_API_URL", "https://api.openai.com/v1")
54
+ ).rstrip("/")
55
+ self.api_key = api_key or os.environ.get("TABELLA_EMBED_API_KEY", "")
56
+ self.model = model or os.environ.get("TABELLA_EMBED_MODEL", "text-embedding-3-small")
57
+ self.dimensions = 0 # discovered from the first response
58
+
59
+ def embed(self, texts: list[str]) -> list[list[float]]:
60
+ import httpx # lazy: hash provider needs no HTTP stack
61
+
62
+ headers = {"Content-Type": "application/json"}
63
+ if self.api_key:
64
+ headers["Authorization"] = f"Bearer {self.api_key}"
65
+ resp = httpx.post(
66
+ f"{self.api_url}/embeddings",
67
+ json={"model": self.model, "input": texts},
68
+ headers=headers,
69
+ timeout=60.0,
70
+ )
71
+ resp.raise_for_status()
72
+ data = sorted(resp.json()["data"], key=lambda d: d["index"])
73
+ vectors = [d["embedding"] for d in data]
74
+ if vectors:
75
+ self.dimensions = len(vectors[0])
76
+ return vectors
77
+
78
+
79
+ def embedding_provider_from_env() -> EmbeddingProvider:
80
+ provider = os.environ.get("TABELLA_EMBED_PROVIDER", "hash")
81
+ if provider == "openai":
82
+ return OpenAICompatibleEmbeddings()
83
+ if provider == "hash":
84
+ return HashEmbeddings(int(os.environ.get("TABELLA_EMBED_DIM", "256")))
85
+ raise ValueError(f"Unknown TABELLA_EMBED_PROVIDER: {provider!r} (hash|openai)")
@@ -0,0 +1,94 @@
1
+ """The vectorization pipeline: records -> chunks -> embeddings -> vector store.
2
+
3
+ Produces the RAG index manifest entry per asset (spec/ai-artifact-manifest.md,
4
+ part 2). Idempotent: re-running replaces the asset's collection.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from tabella_core.connectors import get_connector
12
+ from tabella_core.interfaces import EmbeddingProvider, VectorStore
13
+ from tabella_core.models import TABELLA_SPEC_VERSION, AssetDescriptor
14
+
15
+ from tabella_enable.rag.chunking import chunk_text
16
+
17
+ _PAGE_SIZE = 500
18
+
19
+
20
+ def collection_name(descriptor: AssetDescriptor) -> str:
21
+ return f"tabella_{descriptor.id.replace('.', '_')}"
22
+
23
+
24
+ def _record_ref(descriptor: AssetDescriptor, record: dict, index: int) -> str:
25
+ pk = descriptor.asset_schema.primary_key
26
+ if pk:
27
+ return ",".join(str(record.get(k)) for k in pk)
28
+ return str(index)
29
+
30
+
31
+ def vectorize_asset(
32
+ descriptor: AssetDescriptor,
33
+ embedder: EmbeddingProvider,
34
+ store: VectorStore,
35
+ ) -> dict[str, Any]:
36
+ """Vectorize one asset per its profile; returns its rag.json index entry."""
37
+ profile = descriptor.enablement.vectorization
38
+ if not profile.enabled:
39
+ raise ValueError(f"Asset '{descriptor.id}' has vectorization disabled")
40
+ content_fields = profile.content_fields or [
41
+ f.name for f in descriptor.asset_schema.fields if f.type.value == "string"
42
+ ]
43
+
44
+ connector = get_connector(descriptor.source.connector)
45
+ chunks: list[dict] = []
46
+ offset = 0
47
+ while True:
48
+ records, _total = connector.fetch(descriptor, limit=_PAGE_SIZE, offset=offset)
49
+ for index, record in enumerate(records):
50
+ text = "\n".join(
51
+ str(record[f]) for f in content_fields if record.get(f) is not None
52
+ )
53
+ ref = _record_ref(descriptor, record, offset + index)
54
+ metadata = {f: record.get(f) for f in profile.metadata_fields}
55
+ for chunk_index, piece in enumerate(
56
+ chunk_text(text, profile.chunking, profile.chunk_size)
57
+ ):
58
+ chunks.append(
59
+ {
60
+ "id": f"{descriptor.id}:{ref}:{chunk_index}",
61
+ "record_ref": ref,
62
+ "content": piece,
63
+ "metadata": metadata,
64
+ }
65
+ )
66
+ if len(records) < _PAGE_SIZE:
67
+ break
68
+ offset += _PAGE_SIZE
69
+
70
+ embeddings = embedder.embed([c["content"] for c in chunks]) if chunks else []
71
+ for chunk, embedding in zip(chunks, embeddings, strict=True):
72
+ chunk["embedding"] = embedding
73
+ dimensions = len(embeddings[0]) if embeddings else embedder.dimensions
74
+
75
+ collection = collection_name(descriptor)
76
+ store.replace_collection(collection, chunks, dimensions)
77
+
78
+ return {
79
+ "asset": descriptor.id,
80
+ "content_fields": content_fields,
81
+ "chunking": {
82
+ "strategy": profile.chunking.value,
83
+ "chunk_size": profile.chunk_size,
84
+ },
85
+ "embedding": {"model": embedder.model, "dimensions": dimensions},
86
+ "store": {"backend": store.name, "collection": collection},
87
+ "metadata_fields": profile.metadata_fields,
88
+ "search_endpoint": {"method": "POST", "path": f"/assets/{descriptor.id}/search"},
89
+ "chunk_count": len(chunks),
90
+ }
91
+
92
+
93
+ def build_rag_manifest(entries: list[dict[str, Any]]) -> dict[str, Any]:
94
+ return {"tabella_version": TABELLA_SPEC_VERSION, "indexes": entries}
@@ -0,0 +1,22 @@
1
+ """Semantic search service: embed the query, search the asset's collection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from tabella_core.interfaces import EmbeddingProvider, VectorStore
8
+ from tabella_core.models import AssetDescriptor
9
+
10
+ from tabella_enable.rag.pipeline import collection_name
11
+
12
+
13
+ class SearchService:
14
+ def __init__(self, embedder: EmbeddingProvider, store: VectorStore):
15
+ self.embedder = embedder
16
+ self.store = store
17
+
18
+ def search(
19
+ self, descriptor: AssetDescriptor, query: str, top_k: int = 5
20
+ ) -> list[dict[str, Any]]:
21
+ (query_embedding,) = self.embedder.embed([query])
22
+ return self.store.search(collection_name(descriptor), query_embedding, top_k)
@@ -0,0 +1,140 @@
1
+ """Vector store backends.
2
+
3
+ - `local` — one JSON file per collection under a directory; pure-python cosine
4
+ search. Zero infrastructure: dev, tests, small catalogs.
5
+ - `pgvector` — production backend (psycopg, lazy import). Built against the
6
+ pgvector SQL surface; live validation happens in the AWS test batch along
7
+ with OM/Glue.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import math
14
+ import os
15
+ from pathlib import Path
16
+
17
+ from tabella_core.interfaces import VectorStore
18
+
19
+
20
+ def cosine(a: list[float], b: list[float]) -> float:
21
+ dot = sum(x * y for x, y in zip(a, b, strict=True))
22
+ norm_a = math.sqrt(sum(x * x for x in a)) or 1.0
23
+ norm_b = math.sqrt(sum(x * x for x in b)) or 1.0
24
+ return dot / (norm_a * norm_b)
25
+
26
+
27
+ class LocalVectorStore(VectorStore):
28
+ name = "local"
29
+
30
+ def __init__(self, directory: str | Path = ".tabella/vectors"):
31
+ self.directory = Path(directory)
32
+
33
+ def _path(self, collection: str) -> Path:
34
+ return self.directory / f"{collection}.json"
35
+
36
+ def replace_collection(
37
+ self, collection: str, chunks: list[dict], dimensions: int
38
+ ) -> None:
39
+ self.directory.mkdir(parents=True, exist_ok=True)
40
+ self._path(collection).write_text(
41
+ json.dumps({"dimensions": dimensions, "chunks": chunks}) + "\n"
42
+ )
43
+
44
+ def search(
45
+ self, collection: str, query_embedding: list[float], top_k: int = 5
46
+ ) -> list[dict]:
47
+ path = self._path(collection)
48
+ if not path.exists():
49
+ raise KeyError(f"No vector collection '{collection}' (run `tabella vectorize`)")
50
+ chunks = json.loads(path.read_text())["chunks"]
51
+ scored = sorted(
52
+ chunks, key=lambda c: cosine(c["embedding"], query_embedding), reverse=True
53
+ )[:top_k]
54
+ return [
55
+ {**{k: v for k, v in c.items() if k != "embedding"},
56
+ "score": round(cosine(c["embedding"], query_embedding), 6)}
57
+ for c in scored
58
+ ]
59
+
60
+
61
+ class PgVectorStore(VectorStore):
62
+ """pgvector backend. Collection = one table `tabella_vec_<slug>`.
63
+
64
+ Requires the `vector` extension. Not yet validated against a live
65
+ database — exercised in the AWS test batch.
66
+ """
67
+
68
+ name = "pgvector"
69
+
70
+ def __init__(self, uri: str | None = None):
71
+ self.uri = uri or os.environ.get("TABELLA_VECTOR_PG_URI", "")
72
+ if not self.uri:
73
+ raise ValueError("PgVectorStore requires TABELLA_VECTOR_PG_URI")
74
+
75
+ def _connect(self):
76
+ import psycopg # lazy
77
+
78
+ return psycopg.connect(self.uri)
79
+
80
+ @staticmethod
81
+ def _table(collection: str) -> str:
82
+ safe = "".join(c if c.isalnum() else "_" for c in collection)
83
+ return f"tabella_vec_{safe}"
84
+
85
+ def replace_collection(
86
+ self, collection: str, chunks: list[dict], dimensions: int
87
+ ) -> None:
88
+ table = self._table(collection)
89
+ with self._connect() as conn:
90
+ conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
91
+ conn.execute(f'DROP TABLE IF EXISTS "{table}"')
92
+ conn.execute(
93
+ f'CREATE TABLE "{table}" (id text PRIMARY KEY, record_ref text,'
94
+ f" content text, metadata jsonb, embedding vector({dimensions}))"
95
+ )
96
+ with conn.cursor() as cur:
97
+ cur.executemany(
98
+ f'INSERT INTO "{table}" VALUES (%s, %s, %s, %s, %s)', # noqa: S608
99
+ [
100
+ (
101
+ c["id"],
102
+ c["record_ref"],
103
+ c["content"],
104
+ json.dumps(c["metadata"]),
105
+ str(c["embedding"]),
106
+ )
107
+ for c in chunks
108
+ ],
109
+ )
110
+
111
+ def search(
112
+ self, collection: str, query_embedding: list[float], top_k: int = 5
113
+ ) -> list[dict]:
114
+ table = self._table(collection)
115
+ with self._connect() as conn:
116
+ rows = conn.execute(
117
+ f'SELECT id, record_ref, content, metadata,' # noqa: S608
118
+ f" 1 - (embedding <=> %s::vector) AS score"
119
+ f' FROM "{table}" ORDER BY embedding <=> %s::vector LIMIT %s',
120
+ (str(query_embedding), str(query_embedding), top_k),
121
+ ).fetchall()
122
+ return [
123
+ {
124
+ "id": r[0],
125
+ "record_ref": r[1],
126
+ "content": r[2],
127
+ "metadata": r[3],
128
+ "score": round(float(r[4]), 6),
129
+ }
130
+ for r in rows
131
+ ]
132
+
133
+
134
+ def vector_store_from_env() -> VectorStore:
135
+ backend = os.environ.get("TABELLA_VECTOR_BACKEND", "local")
136
+ if backend == "local":
137
+ return LocalVectorStore(os.environ.get("TABELLA_VECTOR_DIR", ".tabella/vectors"))
138
+ if backend == "pgvector":
139
+ return PgVectorStore()
140
+ raise ValueError(f"Unknown TABELLA_VECTOR_BACKEND: {backend!r} (local|pgvector)")
tabella_enable/rest.py ADDED
@@ -0,0 +1,118 @@
1
+ """Generated REST access layer (spec/access-layer-contract.md).
2
+
3
+ `build_app(catalog)` returns a FastAPI app serving every asset in the catalog
4
+ with `enablement.api: true` through the standard Tabella endpoints.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from fastapi import FastAPI, Request
12
+ from fastapi.responses import JSONResponse
13
+ from tabella_core.connectors import get_connector
14
+ from tabella_core.models import AssetDescriptor, FieldType
15
+
16
+ _RESERVED_PARAMS = {"limit", "offset"}
17
+ _UNFILTERABLE = {FieldType.binary, FieldType.unknown}
18
+
19
+
20
+ class _ApiError(Exception):
21
+ def __init__(self, status: int, code: str, message: str):
22
+ self.status, self.code, self.message = status, code, message
23
+
24
+
25
+ def _coerce(value: str, ftype: FieldType) -> Any:
26
+ try:
27
+ if ftype == FieldType.integer:
28
+ return int(value)
29
+ if ftype == FieldType.number:
30
+ return float(value)
31
+ if ftype == FieldType.boolean:
32
+ if value.lower() in ("true", "1"):
33
+ return 1
34
+ if value.lower() in ("false", "0"):
35
+ return 0
36
+ raise ValueError(value)
37
+ except ValueError:
38
+ raise _ApiError(400, "invalid_value", f"Invalid {ftype.value} value: {value!r}") from None
39
+ return value
40
+
41
+
42
+ def build_app(catalog: list[AssetDescriptor], *, search=None) -> FastAPI:
43
+ """`search` is an optional tabella_enable.rag.SearchService for the
44
+ POST /assets/{id}/search endpoint on vectorized assets."""
45
+ served = [d for d in catalog if d.enablement.api]
46
+ by_id = {d.id: d for d in served}
47
+ app = FastAPI(title="Tabella Access Layer", version="0.1.0")
48
+
49
+ @app.exception_handler(_ApiError)
50
+ async def _handle(request: Request, exc: _ApiError) -> JSONResponse:
51
+ return JSONResponse(
52
+ status_code=exc.status,
53
+ content={"error": {"code": exc.code, "message": exc.message}},
54
+ )
55
+
56
+ def _get(asset_id: str) -> AssetDescriptor:
57
+ if asset_id not in by_id:
58
+ raise _ApiError(404, "asset_not_found", f"No asset '{asset_id}'")
59
+ return by_id[asset_id]
60
+
61
+ @app.get("/health")
62
+ def health() -> dict[str, str]:
63
+ return {"status": "ok"}
64
+
65
+ @app.get("/assets")
66
+ def list_assets() -> dict[str, Any]:
67
+ return {"data": [d.summary() for d in served]}
68
+
69
+ @app.get("/assets/{asset_id}")
70
+ def get_asset(asset_id: str) -> dict[str, Any]:
71
+ return _get(asset_id).to_json_dict()
72
+
73
+ @app.get("/assets/{asset_id}/records")
74
+ def query_records(
75
+ asset_id: str, request: Request, limit: int = 100, offset: int = 0
76
+ ) -> dict[str, Any]:
77
+ descriptor = _get(asset_id)
78
+ limit = max(1, min(limit, descriptor.access.row_limit))
79
+ offset = max(0, offset)
80
+
81
+ filters: dict[str, Any] = {}
82
+ for name, value in request.query_params.items():
83
+ if name in _RESERVED_PARAMS:
84
+ continue
85
+ field = descriptor.asset_schema.field(name)
86
+ if field is None:
87
+ raise _ApiError(400, "unknown_field", f"No field '{name}' in asset '{asset_id}'")
88
+ if field.type in _UNFILTERABLE:
89
+ raise _ApiError(400, "invalid_value", f"Field '{name}' is not filterable")
90
+ filters[name] = _coerce(value, field.type)
91
+
92
+ connector = get_connector(descriptor.source.connector)
93
+ records, total = connector.fetch(descriptor, filters=filters, limit=limit, offset=offset)
94
+ return {
95
+ "data": records,
96
+ "pagination": {"limit": limit, "offset": offset, "total": total},
97
+ "asset": asset_id,
98
+ }
99
+
100
+ @app.post("/assets/{asset_id}/search")
101
+ async def semantic_search(asset_id: str, request: Request) -> dict[str, Any]:
102
+ descriptor = _get(asset_id)
103
+ if not descriptor.enablement.vectorization.enabled:
104
+ raise _ApiError(400, "not_vectorized", f"Asset '{asset_id}' is not vectorized")
105
+ if search is None:
106
+ raise _ApiError(503, "search_unavailable", "Semantic search is not configured")
107
+ body = await request.json()
108
+ query = body.get("query")
109
+ if not isinstance(query, str) or not query.strip():
110
+ raise _ApiError(400, "invalid_value", "Body must include a non-empty 'query'")
111
+ top_k = min(int(body.get("top_k", 5)), 50)
112
+ try:
113
+ results = search.search(descriptor, query, top_k)
114
+ except KeyError as exc:
115
+ raise _ApiError(409, "not_indexed", str(exc)) from None
116
+ return {"data": results, "asset": asset_id, "query": query}
117
+
118
+ return app
@@ -0,0 +1,96 @@
1
+ """AI tool manifest generator (spec/ai-artifact-manifest.md, part 1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ from tabella_core.models import TABELLA_SPEC_VERSION, AssetDescriptor, Classification, FieldType
9
+
10
+ _JSON_TYPES = {
11
+ FieldType.string: "string",
12
+ FieldType.integer: "integer",
13
+ FieldType.number: "number",
14
+ FieldType.boolean: "boolean",
15
+ FieldType.date: "string",
16
+ FieldType.datetime: "string",
17
+ FieldType.json: "string",
18
+ }
19
+
20
+
21
+ def _tool_name(asset_id: str) -> str:
22
+ return "query_" + re.sub(r"[^a-zA-Z0-9_-]", "_", asset_id)
23
+
24
+
25
+ def build_tool(descriptor: AssetDescriptor, *, include_pii_filters: bool = False) -> dict[str, Any]:
26
+ filterable = [
27
+ f
28
+ for f in descriptor.asset_schema.fields
29
+ if f.type in _JSON_TYPES and (include_pii_filters or not f.pii)
30
+ ]
31
+ properties: dict[str, Any] = {
32
+ f.name: {
33
+ "type": _JSON_TYPES[f.type],
34
+ **({"description": f.description} if f.description else {}),
35
+ }
36
+ for f in filterable
37
+ }
38
+ properties["limit"] = {"type": "integer", "default": 100}
39
+ properties["offset"] = {"type": "integer", "default": 0}
40
+
41
+ about = f" ({descriptor.description})" if descriptor.description else ""
42
+ return {
43
+ "name": _tool_name(descriptor.id),
44
+ "description": (
45
+ f"Query the '{descriptor.name}' asset{about}. "
46
+ f"Equality filters on: {', '.join(f.name for f in filterable) or 'none'}. "
47
+ "Returns records as JSON objects."
48
+ ),
49
+ "input_schema": {
50
+ "type": "object",
51
+ "properties": properties,
52
+ "additionalProperties": False,
53
+ },
54
+ "asset": descriptor.id,
55
+ "endpoint": {"method": "GET", "path": f"/assets/{descriptor.id}/records"},
56
+ }
57
+
58
+
59
+ def build_manifest(
60
+ catalog: list[AssetDescriptor],
61
+ *,
62
+ include_restricted: bool = False,
63
+ include_pii_filters: bool = False,
64
+ ) -> dict[str, Any]:
65
+ included = [
66
+ d
67
+ for d in catalog
68
+ if d.enablement.mcp
69
+ and (include_restricted or d.classification != Classification.restricted)
70
+ ]
71
+ tools = [build_tool(d, include_pii_filters=include_pii_filters) for d in included]
72
+ tools += [build_search_tool(d) for d in included if d.enablement.vectorization.enabled]
73
+ return {"tabella_version": TABELLA_SPEC_VERSION, "tools": tools}
74
+
75
+
76
+ def build_search_tool(descriptor: AssetDescriptor) -> dict[str, Any]:
77
+ about = f" ({descriptor.description})" if descriptor.description else ""
78
+ return {
79
+ "name": "search_" + re.sub(r"[^a-zA-Z0-9_-]", "_", descriptor.id),
80
+ "description": (
81
+ f"Semantic search over the '{descriptor.name}' asset{about}. "
82
+ "Pass a natural-language query; returns the most relevant text "
83
+ "chunks with citation metadata and similarity scores."
84
+ ),
85
+ "input_schema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "query": {"type": "string", "description": "Natural-language search query"},
89
+ "top_k": {"type": "integer", "default": 5},
90
+ },
91
+ "required": ["query"],
92
+ "additionalProperties": False,
93
+ },
94
+ "asset": descriptor.id,
95
+ "endpoint": {"method": "POST", "path": f"/assets/{descriptor.id}/search"},
96
+ }
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.5
2
+ Name: tabella-enable
3
+ Version: 0.1.0
4
+ Summary: Tabella AI-enablement: generated REST access layers, MCP tools + live MCP server, RAG vectorization and semantic search
5
+ Project-URL: Homepage, https://github.com/Inceptium-ai/tabella
6
+ Project-URL: Repository, https://github.com/Inceptium-ai/tabella
7
+ Project-URL: Issues, https://github.com/Inceptium-ai/tabella/issues
8
+ Author: Yazdan Ahmed
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: fastapi>=0.111
21
+ Requires-Dist: httpx>=0.27
22
+ Requires-Dist: mcp>=1.2
23
+ Requires-Dist: tabella-core
24
+ Description-Content-Type: text/markdown
25
+
26
+ # tabella-enable
27
+
28
+ AI-enablement generators: the standardized REST access layer
29
+ (`spec/access-layer-contract.md`) and the MCP-aligned tool manifest
30
+ (`spec/ai-artifact-manifest.md`). M2 adds the live MCP server and RAG
31
+ vectorization (chunking, embeddings, pgvector).
@@ -0,0 +1,14 @@
1
+ tabella_enable/__init__.py,sha256=SoyGKT-fhkyzgu04vtumMq2-5YVX2Tp2KLcwTlEMQwo,220
2
+ tabella_enable/mcp_server.py,sha256=2OtRloIfqX-lIOc0T0UCS4Qn3xb8iPClzvDp_q_txPM,3252
3
+ tabella_enable/rest.py,sha256=LmaJjTI5GAISpF5isf15QYUc1t53DfsryUx33_wMxG0,4573
4
+ tabella_enable/tools.py,sha256=IBSMK2F8eh1nNtSf_7GBc7z3ekcvQDjz812CpVdJ__k,3348
5
+ tabella_enable/rag/__init__.py,sha256=ttNKqDsp4IilULXvT5KhF6pPVoWWvmTYKhMEUWx5In8,445
6
+ tabella_enable/rag/chunking.py,sha256=8fvXR2lPze1iAeQ5_ppuVQ59UNlQbQVOVMTfsQtXZ6I,1495
7
+ tabella_enable/rag/embeddings.py,sha256=nse6A9qcB1tvnx8VjEXC5jjUD0maMEALP26OPaqEv4c,3024
8
+ tabella_enable/rag/pipeline.py,sha256=cuqxNYiZgMRLBSwAIM2FrD8oQUV14SNqmJX77qWf1B4,3485
9
+ tabella_enable/rag/search.py,sha256=Bh1cUBuL_aeah2S1IUdr1-nWbXe8OIKm8CRyne2oLps,730
10
+ tabella_enable/rag/store.py,sha256=1jJCmBZm-kfkAdg3vCzhQO9MvuWxcUGFUZm7ghcQ8yo,4930
11
+ tabella_enable-0.1.0.dist-info/METADATA,sha256=hKj0VrAJ7TG9HrkPVAu6wIq1Ufjm2siBvZqQdGIOzdk,1285
12
+ tabella_enable-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
13
+ tabella_enable-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
14
+ tabella_enable-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.