keygraph MCP server
Commit Nov 14, 2026Provides schema context like join paths, keys, and status codes to LLM agents via MCP to improve text-to-SQL accuracy.
Also known as alikarami76/keygraph
- Stars
- 3
- Tools
- —
- Downloads, 30 days
- —
- Latest version
- —
- Last commit
- Nov 14, 2026
- License
- MIT
What is keygraph MCP?
keygraph provides schema context like join paths, keys, and status codes to LLM agents via MCP to improve text-to-SQL accuracy.
Summary generated from the project's README
About keygraph MCP server
Developers building text-to-SQL or data analyst agents can use keygraph to provide essential schema context that prevents common LLM errors like incorrect joins or misinterpreting status codes. By reading database metadata once, it creates a map containing join paths, keys, indexes, table grain, and business context. This map is served to agents via an MCP server, a JSON-enabled CLI, or markdown files, ensuring that large schemas do not overwhelm context windows.
Users can connect to MySQL, MariaDB, PostgreSQL, SQLite, SQL Server, ClickHouse, Metabase, and MongoDB. The system is safe by design because it only reads metadata and masks personal data during value profiling. It includes fifteen MCP tools, such as search, describe, path, and keys, along with a query logging tool. Beyond AI agents, people can explore the schema through an offline HTML explorer or a CLI.
What you can do with it
- 1Find join paths between tablesAn agent can request ranked join routes between two specific tables to avoid guessing join columns.
- 2Resolve business term locationsA developer can ask the agent to identify which tables contain specific business concepts like net revenue.
- 3Interpret status codes and enumsAn agent can look up the meaning of specific column values to ensure SQL filters are accurate.
- 4Optimize queries using indexesAn agent can identify which columns to use in filters to match existing database indexes.
Written from the project's README. Every use case is checked against a quote from it.
Configuration
TABLE_SCHEMA
Automated checks
Ran Nov 14, 2026Full report →Not verified yet. A server needs a score of 80, no serious finding, and enough data for us to check. How checks work · What to fix for more points
- Source repository linked and reachablealikarami76/keygraph is public and reachablegithub.com/alikarami76/keygraph ↗Pass
- Package names this repository as its sourceNot checked
- Build provenance (Sigstore attestation)Not checked
- Open source license (OSI)MITspdx.org/licenses/MIT.html ↗Pass
- Commit or release in the last yearLast commit or release 2026-11-12github.com/alikarami76/keygraph ↗Pass
- OpenSSF ScorecardNot checked
- Package name not close to a popular packageNot checked
- No critical advisory in the package or its dependenciesNot checked
- No hidden instructions to the model0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersPass
- Destructive tools are labelledNot checked
- Remote endpoint answers the MCP handshakeNot checked
README
View on GitHubkeygraph
keygraph is an open-source schema map for people building a data analyst agent, a text-to-SQL agent or any other LLM agent that answers questions from a database. It maps how your tables connect (keys, indexes, declared and inferred foreign keys, grain, status codes, business context and value profiles) and serves that schema context to agents through an MCP server, a CLI with --json, or markdown files, and to people through an offline HTML explorer. It reads only metadata, makes no LLM calls, and gives the same output for the same input. It can also link your source code to the same tables and columns (where each column is declared, written, read and used) and keep a log of the queries people and agents ran, with their timing and the business question behind them.
At a glance. MIT licence. Python 3.11 or newer. Reads MySQL, MariaDB, PostgreSQL, SQLite, SQL Server, ClickHouse, Metabase and MongoDB, or information_schema dumps. Fifteen MCP tools: fourteen read-only and one that logs a query. Runs without a server, and the bundled demo webshop has 35 tables in three schemas. Jump to: build a data analyst agent, quickstart, MCP setup, FAQ.
Why a prebuilt map beats no context or context made on the fly
An agent that writes SQL needs to know which tables exist, how they join, what one row means and what the codes in a column stand for. There are three ways to give it that.
No context at all. The agent guesses table names and joins on columns that look alike. It cannot see that a table holds one row per order line rather than per order, so its sums double count. It does not know that status = 4 means "cancelled". The SQL runs and returns a number, and nothing tells you the number is wrong.
Context the agent makes itself. The agent queries information_schema and samples rows at the start of each session, or asks an LLM to describe the tables. This helps, with four costs:
- the same exploration is repeated in every session, which costs time, tokens and load on the database;
- a large database does not fit in a context window. A 10,000-table warehouse has well over 100,000 columns, so the agent sees only the slice it happened to open and misses the join path that runs through a table it never looked at;
- the result changes from run to run. LLM-written descriptions can be confidently wrong, and nothing marks which parts are guesses;
- sampled rows can carry personal data straight into prompts and logs.
A map built in advance (keygraph). keygraph reads the metadata once and stores the result:
- Whole schema, small prompts. Join paths, hub tables and business areas are computed by code over the whole database. The agent asks for only what it needs, such as one path or one table page, so it doesn't load the schema into its prompt.
- Same answer every time. There are no LLM calls, and the same input always gives the same output, so the map can be reviewed and versioned in git like code.
- Guesses are labelled. Every inferred relation carries a confidence and the reason it was inferred. Curated business context is marked verified or unverified, so the agent knows what to double-check.
- Knowledge accumulates. Grain, status codes, pitfalls and corrections are written down once and reused by every person and agent, instead of being rediscovered and forgotten in each session.
- Safe by construction. It reads metadata only, value profiles mask personal data, and agents query the map instead of the production database.
- One map for people and agents. The HTML explorer, the CLI, the MCP server and the markdown pages all read the same graph.
| No context | Made on the fly | keygraph | |
|---|---|---|---|
| Covers the whole schema | no | only what fits in the prompt | yes |
| Cost per question | low, but answers are often wrong | repeated exploration every session | one lookup |
| Same answer each run | no | no | yes |
| Shows which joins are guesses | no | no | yes, with confidence and reason |
| Business meaning of codes and grain | no | rediscovered, then lost | stored, curated, reused |
| Personal data in prompts | no | often | masked |
How do I build a data analyst agent with keygraph?
Build the map once with keygraph scan, then let your agent look up tables, join paths and keys through MCP or the CLI before it writes any SQL. keygraph works with any agent that can call MCP tools or run a CLI, including Claude Code and the Claude Agent SDK, and agents written with LangChain, LlamaIndex or your own tool-calling loop. It exposes three interfaces (MCP, CLI --json and markdown files) and no framework-specific plugins.
The problem it solves. An LLM that writes SQL against a database it has never seen tends to fail in three ways. It invents joins from column names that look alike. It misses the grain of a table, so a sum over order lines is counted twice. It misreads codes, such as treating status = 4 as something other than "cancelled". The query runs, returns a number, and nothing says the number is wrong.
The loop. An agent that uses keygraph follows the same six steps for each question. The order is the one recommended in AGENTS.md.
searchthe business term (for example "net revenue") to find candidate tables and see why each one matched.describeeach candidate to read its grain, keys, columns, status codes and pitfalls (describe --brief, orbrief=trueover MCP, returns just keys, filter columns, notes and columns as name, type, key and codes: a cheaper first look at a wide table).pathbetween the tables to get ranked join routes with confidence, evidence, fan-out warnings and aJOINsnippet. Do not write a join from column-name guesses whenpathcan answer it.keyson the large tables to pick filters that match an index, leading with the first column of an index.- Write the SQL and run it with your own read-only database access. keygraph has no tool for running your queries: it only reads metadata, and samples values when you ask it to profile. Before you write it, if code or past queries were indexed,
code_whereshows how a column is used in code andquery_forshows queries that already touched the table, with their business question and timing. - Check the result against what the map said: aggregate before a fan-out join, treat relations below 0.6 confidence as unverified, and verify them with a small
SELECT. Then log the query you ran withquery_submit(orkeygraph queries add), so the next agent can reuse a proven query shape.query_submitonly records; keygraph still runs nothing.
Register the MCP server once and the fifteen tools appear in your agent (the configs for other clients are in MCP):
claude mcp add keygraph -- uvx --from 'keygraph[mcp]' keygraph mcp --dir /abs/path/to/out
If your agent cannot use MCP, have it run the same commands with --json, for example keygraph path orders shipments --json, or let it read areas/<area>.md and tables/<schema.table>.md as ordinary files. When the agent confirms what a table or status code means, keygraph context add saves it, so the next question starts from better context.
When to use keygraph
Use keygraph when you need to:
- find the join path between two tables, with the join columns, a confidence for each hop and a ready
JOINsnippet; - infer missing foreign keys in a database that declares few or none;
- get an ER diagram of an existing database, grouped into business areas so it stays readable;
- give an LLM agent schema context for text-to-SQL: keys, indexes, join paths, grain, status codes and pitfalls, through MCP, a CLI with
--json, or markdown files; - find which table holds a business concept such as "net revenue" or "in transit";
- learn what an enum or status code means, and compare the documented codes with the values actually in the data;
- profile column values (top values, empty rate, ranges) with personal data masked;
- browse a data catalog from one offline HTML file, without running a server.
Quickstart
With your AI agent. Paste this into Claude Code, Codex, Cursor, ZCode, OpenCode, Unsloth Studio or any other coding agent:
Set up keygraph for this project. Follow https://github.com/alikarami76/keygraph/blob/main/setup/SETUP.md exactly.
The agent detects your database and its own harness, then asks you up to six questions. It builds the map, connects keygraph over MCP, and checks the result with keygraph doctor. Your credentials never go into a config file. Details are in setup/.
By hand. keygraph needs Python 3.11 or newer. Install it, build a graph from a live database, and open the explorer:
pip install 'keygraph[live]' # or: uvx --from 'keygraph[live]' keygraph ...
keygraph scan --url postgresql://user@host/db --schema public # read-only metadata scan, writes ./keygraph-out
keygraph ui # opens keygraph-out/keygraph.html
keygraph doctor # checks the install, the map and the MCP server
scan takes any SQLAlchemy URL, so add the driver for your database (for example psycopg for PostgreSQL or pymysql for MySQL). For MySQL/MariaDB, PostgreSQL, SQL Server and ClickHouse URLs, scan uses that engine's own adapter, so the map keeps column comments, enum members, row-count estimates and partitions (SELECT-only, the same as load); SQLite and other databases use the SQLAlchemy inspector. --schema and --all-schemas work the same on both paths (without them, the connected database for MySQL and ClickHouse, and the connection's current schema for PostgreSQL and SQL Server; a scan that finds no tables stops with a message suggesting --schema or --all-schemas). If the adapter fails, scan warns on stderr and falls back to the inspector; --generic forces the inspector. build.json records which path was used. Then ask questions from the command line:
keygraph describe orders --brief # keys, filter columns, notes and columns as name/type/key/codes only
keygraph search "monthly revenue" --no-paths # skip the suggested join paths
keygraph path customers shipments # ranked join paths with a JOIN snippet
keygraph search "monthly revenue" # which tables hold this
keygraph keys orders # primary key, unique keys, indexes in column order
To try it without a database, clone the repository and build the bundled fictional webshop (35 tables, three schemas):
git clone https://github.com/alikarami76/keygraph && cd keygraph
uv sync && uv run bash examples/shop/build.sh && uv run keygraph ui --dir examples/shop/out
The build writes graph.json, RELATIONS_REPORT.md, keygraph.html (a self-contained explorer that works from disk, offline), keygraph.db (SQLite with full-text search) the agent pages areas/*.md and tables/*.md, and build.json (build time, keygraph version, source kind and database name, covered schemas; no host or credentials; the only file that differs between two identical builds, and SOURCE_DATE_EPOCH fixes its time). An unknown-table answer names the schemas the map covers. Details of every step are in How keygraph works (PDF) and examples/shop.
If you cannot connect to the database, build from information_schema dumps instead:
keygraph load --columns columns.jsonl [--statistics stats.jsonl] [--key-columns kcu.jsonl] [--tables tables.jsonl]
Dumps use information_schema field names. --columns-map '{"TABLE_SCHEMA":"db"}', --flatten raw and --where field=value adapt other shapes. Without STATISTICS the tool falls back to COLUMN_KEY (PRI/UNI/MUL), and without KEY_COLUMN_USAGE every relation is inferred. keygraph fetch --cmd 'my-sql-cli --sql {sql}' --out dir fetches those two tables through any read-only command that prints JSON rows.
Supported sources
Each source is a module in keygraph.adapters, read-only by construction. SQL statements pass assert_select (a single SELECT, no write keywords, no INTO OUTFILE or FOR UPDATE); SQLite is read through the SQLAlchemy inspector, and MongoDB and Metabase are limited to the calls listed below.
| Source | What keygraph reads | How you use it |
|---|---|---|
| MySQL, MariaDB | information_schema (columns, indexes with column order, foreign keys, table facts, enum members) |
keygraph scan --url, dumps, or the mysql adapter |
| PostgreSQL | information_schema and pg_catalog (indexes, foreign keys, enum types, row estimates, comments, checks) |
keygraph scan --url, or the postgres adapter |
| SQLite | the SQLAlchemy inspector (metadata only) | keygraph scan --url sqlite:///file.db |
| SQL Server | INFORMATION_SCHEMA and sys.*; samples use SELECT TOP n |
keygraph scan --url, the sqlserver adapter, keygraph profile --source sqlserver |
| ClickHouse | system.tables, system.columns, system.data_skipping_indices; the primary key becomes the PRIMARY index, ORDER BY an index |
keygraph scan --url, the clickhouse adapter, keygraph profile --source clickhouse |
| Metabase | REST GET /api/database/:id/metadata (tables, fields, semantic types, foreign-key targets, field fingerprints) and native SELECTs through POST /api/dataset; no other request |
metabase adapter (Python API) |
| MongoDB | schema inferred from sampled documents (nested paths become columns), indexes, _id as primary key, DBRef values as references; only list_collection_names, find, index_information and estimated_document_count can be called |
mongodb adapter, keygraph profile --source mongodb |
information_schema dumps (JSON, JSONL, CSV) |
the files you give it | keygraph load |
| Any read-only command that prints JSON rows | the rows | keygraph fetch --cmd |
The Python entry point for the adapters is keygraph.adapters.open_source(kind, ...), which returns an object with schema() and sample().
Explorer views
keygraph.html is one file with no network requests. It is organised around the questions people ask: where does something live, how does it connect, what is in it. A canvas never draws more than 40 boxes: bigger areas are grouped and say what they hide, and an area over 25 tables first shows its 25 most connected tables.
Areas. The map of the whole database. Each box is a business area; the number on a line is how many relations join two areas. Start here when you do not know where something lives.
Area. One area as a table diagram. Lines attach to the exact column that joins. Solid lines are declared foreign keys, dashed lines are inferred and carry their confidence. Hubs (tables that half the database points to) appear as a small label on each box instead of as dozens of lines.
Path. Pick two tables and get ranked routes, a copyable JOIN, and a warning at every step that can multiply rows (fan-out).
Table. One page per table: what a row is, pitfalls, the metrics that use it, and every column with its keys, value ranges and empty rate.
Search. Type a business word. Metrics, concepts, tables, columns and profiled values come from one index, so a status label such as "in transit" finds the column that stores it. Each result says why it matched.
There is also a Column view that sets documented status codes next to the values found in a sample. All screenshots come from the fictional demo in examples/shop.
Use with AI agents
An agent can use the same graph four ways: MCP tools, the Claude Code skill, the CLI with --json, and plain markdown files. The recommended order for an agent is in AGENTS.md: search or list the areas, describe the table, find the path before writing any join, and use keys to choose index-friendly filters.
Every query command (search, describe, keys, explain, path, neighbors, areas, area, code where|what|stats, queries top|slow|for|search|show|stats) takes --json. The build also writes areas/index.md, areas/<area>.md (tables, joins and a Mermaid ER diagram) and tables/<schema.table>.md (grain, keys, columns, relations in both directions) that an agent can read like any other file.
The Claude Code skill is in skills/keygraph/SKILL.md. It tells an agent when to use each command and how to read confidence.
MCP
keygraph mcp serves keygraph's queries to any MCP client over stdio. It needs the mcp extra and a built output
directory (<out> below, e.g. keygraph-out). Tools (describe takes brief=true, search takes with_paths=false, the same as the CLI describe --brief and search --no-paths): search, describe, keys, explain, path, neighbors,
areas, area, profile_summary (stored, sampled profiles; PII values are withheld), code_where and code_what
(the code index), query_for, query_top and query_search (the query log), and query_submit, the one tool that
writes: it logs a query the agent ran into the query log tables and nothing else. Each returns the same JSON as
the CLI's --json, except that areas wraps the list of areas as {"areas": [...]} because MCP tool results must be objects. path, areas and area take include_mirrors. Resources: keygraph://areas/index and
keygraph://tables/{schema.table}. The server never runs SQL against your database.
Use absolute paths for --dir and --directory. GUI clients (Claude Desktop, Cursor) often do not see your shell
PATH, so put the absolute path to uvx or uv (which uvx) in command if the server fails to start. The checkout
variant runs from a clone: uv --directory /abs/path/to/keygraph run --extra mcp keygraph mcp --dir /abs/path/to/out.
Claude Code:
claude mcp add keygraph -- uvx --from 'keygraph[mcp]' keygraph mcp --dir /abs/path/to/out
claude mcp add keygraph -- uv --directory /abs/path/to/keygraph run --extra mcp keygraph mcp --dir /abs/path/to/out
Claude Desktop (claude_desktop_config.json) and Cursor (.cursor/mcp.json):
{
"mcpServers": {
"keygraph": {
"command": "uvx",
"args": ["--from", "keygraph[mcp]", "keygraph", "mcp", "--dir", "/abs/path/to/out"]
}
}
}
{
"mcpServers": {
"keygraph": {
"command": "uv",
"args": ["--directory", "/abs/path/to/keygraph", "run", "--extra", "mcp", "keygraph", "mcp", "--dir", "/abs/path/to/out"]
}
}
}
Codex (~/.codex/config.toml):
[mcp_servers.keygraph]
command = "uvx"
args = ["--from", "keygraph[mcp]", "keygraph", "mcp", "--dir", "/abs/path/to/out"]
# or, from a checkout
[mcp_servers.keygraph]
command = "uv"
args = ["--directory", "/abs/path/to/keygraph", "run", "--extra", "mcp", "keygraph", "mcp", "--dir", "/abs/path/to/out"]
(Use one [mcp_servers.keygraph] block, not both.)
keygraph MCP questions
Does keygraph make LLM calls?
No, it reads only metadata and makes no LLM calls, ensuring consistent output.
What databases does keygraph support?
It supports MySQL, MariaDB, PostgreSQL, SQLite, SQL Server, ClickHouse, Metabase, and MongoDB.
Can keygraph run SQL queries?
No, keygraph is read-only and does not have a tool for running queries; it only reads metadata and profiles values.
How can I use keygraph with an AI agent?
You can use it via an MCP server, a CLI with JSON output, or by reading generated markdown files.