Built with Tutify.io

    AIStudyLabs

    How to Build a Context Layer for AI: A Step-by-Step Architecture

    How to Build a Context Layer for AI: A Step-by-Step Architecture

    Many teams that try to build a context layer start in the wrong place. They buy or install a catalog, run the crawlers, and end up with forty thousand described tables and an agent that's no more accurate than before. The work that makes agents accurate is narrower and more boring: deciding what a handful of metrics mean, which tables to trust, who may see what, and how you'll know the agent got it right.

    This guide lays out that work in order. Each step names open-source options and the mistakes that cost the most time. It's the practical end of a series on the context layer for AI, so if you haven't read it yet, the series overview on what a context layer is explains the parts before you assemble them.

    Why build a context layer at all?

    Because agents fail on enterprise data in predictable ways. They pick the wrong table, use the wrong definition of a metric, join through the wrong key or read data the user shouldn't see. Better models don't fix any of those, because the missing information isn't in the model.

    Gartner put the stakes in a February 2025 release: through 2026, organizations will abandon 60% of AI projects unsupported by AI-ready data. It also reported that 63% of organizations don't have, or aren't sure they have, the right data management practices for AI. The 60% figure applies only to projects without AI-ready data, not to all AI projects.

    AI-ready data isn't a product you install. It's data whose meaning, quality, lineage and access rules are written down where a machine can use them. A context layer for AI is where you write them down.

    Diagram of the seven steps to build a context layer: pick use cases and golden questions, certify data, define metrics and glossary, capture lineage and policies, add documents and memory, serve through MCP, then evaluate and improve in a loop back to step one

    What AI-ready data means in practice

    "AI-ready data" sounds like a property of the data itself. In practice it's a property of the data plus what's written down about it. A table is AI-ready for a given use case when an agent can find it, understand what each column means, know whether to trust it, and know who may see which rows. The same table can be AI-ready data for one use case and not for another.

    That's why the steps below start from use cases. There's no way to make all data AI-ready at once, and trying is how catalog projects stall. Scope the work to the questions you need answered, and AI-ready data becomes a short list you can finish.

    Step 1: Pick use cases and write golden questions

    Start with one to three use cases, not the whole company. "Sales managers asking about pipeline and revenue" is a use case. "Make all our data AI-ready" is not.

    For each use case, collect 30 to 200 real questions users will ask, and get a data owner to verify the answer to each one. These golden questions are your test set for everything that follows. There's no standard size for this set. Practitioners tend to start small and grow it as failures show up.

    Include a few questions the agent should refuse, such as questions about deprecated systems or data the user can't access. An agent that answers everything isn't accurate, it's reckless.

    Writing the golden questions also surfaces disagreements early. If finance and sales give different answers to "what was revenue last quarter?", you've found the first definition to settle, before any tooling is involved.

    Step 2: Certify the data in a metadata catalog

    List the tables, models and documents your golden questions depend on. Often that's a few dozen tables, not thousands. For each one, record:

    A metadata catalog is the natural home for this. Open-source options include DataHub, OpenMetadata and Unity Catalog OSS. DataHub and OpenMetadata describe assets, owners and glossary terms, Unity Catalog OSS covers assets, ownership and access, and DataHub and OpenMetadata ship MCP servers that let agents search them.

    The mistake here is documenting everything. A metadata catalog with forty thousand descriptions and no certification flags gives an agent forty thousand ways to be wrong. Certify the small set you need and mark everything else as untrusted.

    Step 3: Define metrics and a glossary

    For metric questions, this step often matters most. A semantic layer defines metrics, dimensions and joins once in code, so every tool computes them the same way. Define the metrics your golden questions use in a semantic layer, in code: dbt MetricFlow, Cube, or your warehouse's own option such as Snowflake semantic views. The agent then asks for "net revenue by region" by name, and the semantic layer compiles the SQL.

    The dbt Semantic Layer for AI agents tutorial walks through defining metrics and exposing them over MCP. For how a semantic layer relates to the wider context layer, and what the accuracy benchmarks show, see context layer vs semantic layer.

    Next to the metrics, write a short business glossary for the terms that cause arguments: "active customer", "region", "churn". Link each term to the metric or column that implements it. Keep it short. Fifty well-defined terms beat five hundred vague ones.

    If your questions depend on relationships beyond simple joins, such as suppliers, parts and products, this is where an ontology or knowledge graph comes in. Knowledge graphs for AI agents covers when that's worth it, and our earlier guide to ontology in data and AI covers the modeling.

    Step 4: Capture lineage and access policies

    Lineage lets an agent explain where a number came from and lets you trace a wrong answer back to its source. OpenLineage is the open standard. It models jobs, runs and datasets, with extra metadata attached as facets, and Marquez is its reference implementation. Many orchestrators and catalogs can emit or ingest it.

    Access policies are the step people skip and regret. The agent must act with the permissions of the person it's working for, or with its own narrowly scoped identity. Never a shared admin account.

    That means:

    Catalogs such as Unity Catalog and Apache Polaris manage table-level policies. Your warehouse handles row and column security.

    Step 5: Add documents and memory, carefully

    Some golden questions will need unstructured knowledge: runbooks, contracts, policy documents. Add them through retrieval, but give every document an owner and a freshness date, and remove the ones nobody owns. Stale documents can be worse than missing ones, because they look authoritative.

    Memory comes last. Store user preferences and corrections a person has confirmed, with timestamps, and make memories easy to inspect and delete. A wrong fact in memory repeats until someone deletes it. The article on context engineering for AI agents covers memory types and how to keep them from poisoning the context window.

    Step 6: Serve the context layer over MCP

    Agents reach all of this through tools, and the Model Context Protocol is the standard way to expose them. A typical setup has two or three servers:

    Keep each server small and focused, and expose only certified assets by default. If you're building your own server, the Model Context Protocol explained includes a Python example that hides uncertified metrics unless the agent asks for them.

    If your data lives in Snowflake or Microsoft Fabric, the platforms bundle much of steps 3 to 6. Snowflake Horizon Context vs Microsoft Fabric IQ compares what each provides and what was still in preview.

    Step 7: Evaluate, then improve

    Run the golden questions against the agent before you change anything, and again after every change. Score numeric answers with a tolerance, and score refusals as correct when refusing was the right answer.

    Here's a minimal evaluation harness:

    import math
    
    # Golden questions: real user questions with answers a data owner has verified.
    GOLDEN = [
        {"id": "q1", "question": "Net revenue in EMEA last quarter?", "expected": 4_210_000, "tolerance": 0.005},
        {"id": "q2", "question": "Active customers in March?", "expected": 18_342, "tolerance": 0},
        {"id": "q3", "question": "Average order value in 2025?", "expected": 87.40, "tolerance": 0.01},
        {"id": "q4", "question": "Revenue from the legacy CRM?", "expected": "refuse", "tolerance": None},
    ]
    
    def score(case, answer):
        if case["expected"] == "refuse":
            return answer == "refuse"
        if not isinstance(answer, (int, float)):
            return False
        return math.isclose(answer, case["expected"], rel_tol=case["tolerance"])
    
    def evaluate(agent_answers):
        passed = 0
        for case in GOLDEN:
            ok = score(case, agent_answers.get(case["id"]))
            passed += ok
            print(f"{case['id']}  {'PASS' if ok else 'FAIL'}  {case['question']}")
        print(f"accuracy: {passed}/{len(GOLDEN)} = {passed / len(GOLDEN):.0%}")
    
    # Illustrative answers: before and after adding governed metrics.
    before = {"q1": 4_890_000, "q2": 18_342, "q3": 91.15, "q4": 1_200_000}
    after = {"q1": 4_208_500, "q2": 18_342, "q3": 87.42, "q4": "refuse"}
    
    print("before:"); evaluate(before)
    print("after:"); evaluate(after)
    

    Output:

    before:
    q1  FAIL  Net revenue in EMEA last quarter?
    q2  PASS  Active customers in March?
    q3  FAIL  Average order value in 2025?
    q4  FAIL  Revenue from the legacy CRM?
    accuracy: 1/4 = 25%
    after:
    q1  PASS  Net revenue in EMEA last quarter?
    q2  PASS  Active customers in March?
    q3  PASS  Average order value in 2025?
    q4  PASS  Revenue from the legacy CRM?
    accuracy: 4/4 = 100%
    

    The answers here are illustrative, not from a real agent. In this example, the "before" answers stand for an agent that included refunds in revenue, computed average order value from the wrong table, and answered from a deprecated system. Each failure points to a specific fix: a metric definition, a certification flag, a policy. A note on scoring: tolerance is relative, so 0.005 means within 0.5%, a tolerance of 0 requires an exact match, a missing or non-numeric answer fails, and a refusal case passes only when the agent refuses. The harness turns "the agent seems better" into a number and a list of failures with causes.

    In production, also log every tool call and every user correction, and route corrections to the owner of the metric or table involved. Over time, the corrections become new golden questions. If you need a governance frame for this loop, NIST's AI Risk Management Framework organizes the work into govern, map, measure and manage functions, and its Generative AI Profile applies them to generative AI systems.

    Who owns the context layer?

    Tools are the easy part to assign. Ownership is harder. One workable split has three parts:

    Write the split down before you build a context layer, not after the first incident.

    A reference architecture to build a context layer with open-source parts

    | Layer | Job | Open-source options | |---|---|---| | Semantic layer | Governed metrics, compiled to SQL | dbt MetricFlow, Cube Core | | Metadata catalog | Assets, owners, certification, glossary | DataHub, OpenMetadata, Unity Catalog OSS | | Lineage | Where data came from | OpenLineage with Marquez | | Table catalog and policies | Table access across engines | Apache Polaris, Unity Catalog OSS | | Relationships | Multi-hop entity questions | A graph database plus an ontology | | Delivery | Tools for agents | MCP servers for each component | | Evaluation | Accuracy over time | Golden questions and a scoring harness |

    You don't need every row on day one. A semantic layer, a small certified set in a metadata catalog, per-user permissions and an evaluation harness will carry most first use cases.

    A 90-day plan to build a context layer for AI

    If you need a timeline to take to your team, here's one you can adapt, assuming one use case and a small team:

    The second use case goes faster, because the metadata catalog, policies, MCP servers and evaluation harness already exist. That's the real return on the first 90 days: you build a context layer once and extend it, instead of rebuilding context for every new agent. A context layer for AI is infrastructure, and it pays off the way infrastructure does, on the second and third use.

    Common mistakes when building a context layer

    Key takeaways