Knowledge Graph for Code Explained: A Practical Guide

Dan Greer · · 21 min read
Visual knowledge graph for code explained with connected nodes and programming symbols

Knowledge graph for code explained sounds abstract until your agent renames one helper, misses two downstream callers, and quietly breaks a cron job. That's the real problem: AI tools can write code fast, but they still miss structure when the repo only looks like files and folders.

What matters is whether you can answer the questions that usually burn an afternoon (or a Friday deploy): what calls this, where does it enter production, and does the same logic already exist somewhere else.

A few things worth getting straight first:

  • A code graph is about relationships, not "smart search"
  • Blast radius beats file reading when you're changing shared code
  • Reachability is the check people skip, then regret later

Read this and you'll stop guessing.

The Problem AI Coding Tools Still Have

You’ve probably seen this one already. You ask Claude Code, Cursor, or Devin Desktop to refactor a shared utility. It changes the obvious files, the diff looks clean, tests pass locally, and then some unrelated endpoint breaks because the agent never saw the callers two hops away.

That pattern keeps repeating because the weak point usually isn’t syntax. It’s structure.

The failure modes are familiar:

  • the agent writes a new helper even though near-identical logic already exists in another module
  • it makes a breaking change because it didn’t trace downstream dependencies
  • it adds code that never gets wired into an endpoint, job, or actual runtime path
  • it burns half the context window reading files just to build a shaky mental model

File-by-file exploration works for toy repos. It gets ugly fast in a product codebase where the same concept shows up across routes, jobs, services, and shared modules. Solo founders feel this early because there’s no spare person doing architecture babysitting.

The core issue is simple: AI tools often explore code like a stranger walking room to room with no blueprint.

A knowledge graph for code turns that blueprint into something queryable before an agent edits anything.

Knowledge graph for code explained with AI coding tool challenges visualized

What a Knowledge Graph for Code Actually Is

Plain version: a knowledge graph for code is a structured map of code entities and the relationships between them.

The entities become nodes. The relationships become edges.

Typical nodes include:

  • functions
  • files
  • modules
  • endpoints
  • cron handlers
  • environment variables

Typical edges include:

  • calls
  • imports
  • exports
  • depends on
  • owned by
  • reachable from

That sounds abstract until you use it to answer actual engineering questions. Not “find this string,” but “what depends on this function?” or “is this export reachable from a production entry point?”

That’s the difference.

A graph is not just a diagram. It’s not just a search box either. It gives you traversable relationships.

Here’s the practical split:

  • AST gives syntax structure
  • grep gives text matches
  • vector search gives similarity
  • a code knowledge graph gives architectural relationships you can walk

If grep finds formatCurrency, that tells you where text appears. If a graph shows formatCurrency -> BillingService -> /api/invoices -> nightly reconciliation job, you can reason about blast radius. Very different job.

Good code context is not more text. It’s better structure.
Diagram showing how a knowledge graph for code connects programming concepts, functions, and data relationships

Grep, embeddings, or a graph?

Start with the question. grep prints the lines that match a pattern, as the GNU grep manual describes, which is handy for a config key, an error message, or a name you already know. A match doesn't tell you which definition a call reaches.

ripgrep searches recursively, respects ignore rules by default, accepts directory paths, and returns matching lines, as its guide explains. In a checkout of cal.diy at 54343aa6, the open-source scheduling app used in the example below, try this (-w matches whole words, -n prints line numbers):

rg -n -w 'checkAdminOrOwner' packages apps

rg prints each matching line with its file and line number. A match could be an import, a definition, a call, or a re-export, so inspect each one before counting callers. packages/platform/libraries/index.ts re-exports the function at that revision, so that match is an export, not a call. The graph result for the same function, in the concrete example below, lists resolved callers instead.

Embeddings offer a different starting point. For a vague request like “find our retry handling,” a vector index can retrieve candidates by similarity, but similarity doesn't say what calls what, so inspect each candidate's connections and read the implementation before treating it as the code in use.

There is a measured tradeoff. In the Codebase-Memory preprint, across 31 repositories, the graph-backed agent scored 83% on answer quality, against 92% for a file-exploration agent, while using one tenth as many tokens and 2.1 times fewer tool calls. On graph-native questions such as caller ranking and hub detection, it matched or beat the explorer on 19 of the 31 languages tested. Both agents ran on one model and the paper's first author graded the answers, so read these as one study's results for another system: not a benchmark of Pharaoh (ours), and not a guarantee that an edit is safe. For our own measurements, see graph queries versus repository packs. For the relationship types, see dependency graphs versus call graphs.

Why Developers Search for This Now

This topic matters more because AI coding moved from “help me write a function” to “help me operate a codebase.” Once agents started touching refactors, reviews, and wiring work, structural blindness became expensive.

The MCP shift made this sharper. Instead of forcing a model to infer everything from raw files, we can give it tools that answer specific questions. That’s a better pattern. Less guessing, less theater.

The mental move is small but important:

  • stop prompting harder
  • start giving the agent a map it can query

I care about whether the agent can show the relationships behind its proposed edit. A useful evaluation checks that evidence alongside the generated code.

So when people search for knowledge graph for code explained, they’re usually not chasing theory. They want a way to stop rediscovering the same repo architecture every session.

How a Code Knowledge Graph Is Built

The pipeline is pretty straightforward when you strip away the buzz.

  1. Connect a repository.
  2. Parse source files.
  3. Extract entities like functions, modules, imports, exports, and endpoints.
  4. Resolve cross-file relationships.
  5. Store the result in a graph database.
  6. Query it through tools or APIs.

The key part is deterministic parsing. Tools like Tree-sitter read source code structure without guessing. That matters because the graph should come from actual code relationships, not from a model improvising what it thinks the repo probably does.

Some systems store the graph in databases built for relationship traversal, such as Neo4j. That’s a good fit because software architecture is mostly a relationship problem.

The graph itself is usually metadata about the codebase, not code generation logic. Different layer. Different job.

I build Pharaoh. It uses a tree-sitter-based parser for TypeScript, JavaScript, Python, C and C++ repositories, maps their structural relationships, and makes that metadata available to coding assistants through MCP.

Deterministic graphs, LLM extraction, and plain RAG

A graph describes the stored relationships. It doesn't tell you how those relationships were obtained, which is the part I'd check before trusting a caller list, especially if the same index also contains generated summaries, semantic groupings, or documentation.

Tree-sitter parses syntax according to a grammar. In a deterministic pipeline, extraction rules select code entities, a resolver connects references, and the stored graph records the result. A careful pipeline also records the references its resolver couldn't close. I prefer this as the basis for a report of callers because I can inspect the extraction rule and source location.

LLM extraction asks a model to identify relationships in text. In Microsoft's GraphRAG dataflow, under the default workflow, text is divided into units, an LLM extracts entities and relationships from each one, and the results are merged. That's a different source of evidence from a resolved call site, even if both outputs use nodes and edges.

Plain RAG retrieves material for a generator, and it can retrieve source code or documentation, but a retrieved passage doesn't establish a call path, so read the relevant code before making that claim. The RAG paper describes retrieval feeding generation.

grep remains useful alongside all of these. Use it to check a literal name, use retrieval when you need candidate passages, and ask the graph for relationships it actually models, then open the code when behavior matters.

Carry the build through to a query

The six-step list at the start of this section describes the build. I'd check each handoff before adding more node types, because parsing a call, resolving its target, keeping the relationship current, and returning it to an agent are separate pieces of work.

Tree-sitter produces a concrete syntax tree, which gives your extractor syntax to work with, while a resolver, in a separate step, connects names to definitions across imports.

  1. Parse files and retain symbol locations.

  2. Resolve references across files and package boundaries.

  3. Identify entry points, including framework-loaded handlers.

  4. Persist the graph with its repository revision and replace outdated relationships when rebuilding.

  5. Expose scoped queries through MCP so the assistant can retrieve a caller path rather than a whole graph dump.

That is a design checklist, and implementations differ. See how tree-sitter parsing builds a code graph.

For the delivery choices, see code graph MCP servers compared.

Where static analysis runs out

Consider a route name read from configuration, a handler selected through dynamic dispatch, or a method found through reflection, and ask what evidence your resolver has for the target. The syntax can be present without enough information to establish the executed path.

rg can help you inspect a string-based registration, but it still returns text matches, so open the registration code, especially when a name becomes an attribute lookup. Python documents that behavior in getattr.

Pharaoh maps the default branch, a live repository re-maps after a push to that branch, and uncommitted changes stay outside the graph, so compare revisions before deciding a path is absent.

What Questions a Knowledge Graph Can Answer That File Search Cannot

This is where the value gets obvious. Most useful codebase questions are relationship questions, not text lookup questions.

A graph helps with codebase mapping:

  • what modules exist
  • how are they connected
  • where are the hot spots

It helps with function search in a way grep can’t:

  • does this logic already exist somewhere else
  • where is the real implementation versus a re-export
  • what calls it in production

It helps with blast radius:

  • what breaks if we rename this function
  • which modules depend on this file
  • what endpoints or jobs are affected downstream

It helps with dead code detection:

  • which exports are never called
  • which modules are imported nowhere meaningful

It helps with reachability:

  • is the code we just added actually connected to an endpoint, cron, CLI task, or worker
  • did we build a feature or just write a dead branch

And it helps with dependency tracing:

  • are these modules tightly coupled
  • do we have circular imports
  • where does the coupling actually start

A graph query answers only for the relationships its mapper records. Check the schema and revision before treating an absent relationship as an architectural finding.

What a useful code graph should record

I'd want evidence attached to an edge before trusting it in a refactor, including the source location, the extraction rule, and the revision it describes. These are schema recommendations for a graph you build or evaluate, rather than a list of extra Pharaoh features.

Keep a direct import separate from a resolved call. If two modules are grouped by naming similarity, label that relationship as inferred, keep its evidence visible, and exclude it from a report of resolved callers. The same applies to tests: an import from a test file, a call made during a test, and measured coverage describe different evidence.

get_blast_radius, Pharaoh's change-impact tool, excludes callers in test files, so inspect tests separately and check the returned production paths against your change. The cal.diy change-impact trace shows that workflow on one function, with timings from three runs with Pharaoh and three without.

get_unused_code, Pharaoh's unused-code tool, separates Dead from Possibly unused, and lists exports that only test files reference as Used only by tests. Dead requires all its signals to agree, meaning no entry point reaches the function, no other file names it, and no production file imports its file. A passing test can still leave a feature disconnected; our feature-wiring fixture demonstrates that case. For a cleanup workflow, see finding unused exports.

A Concrete Example: From Blind Refactor to Informed Change

As a hypothetical example, take a shared notification formatter used by billing emails, in-app alerts, and a failed-payment cron job.

Before the graph, an agent edits formatNotificationPayload() in isolation. It updates the direct unit tests and maybe one obvious caller. Looks fine. Hidden problem: two indirect callers depend on a field the refactor removed.

That’s where regressions come from. Not from dramatic mistakes. From missing one quiet path.

After the graph, the workflow changes. Before editing, the agent checks dependency paths and reachability.

Here is an actual Pharaoh get_blast_radius result for checkAdminOrOwner in the Pharaoh-so/cal.diy fork, revision 54343aa6, captured on 2026-10-26. This excerpt is trimmed by removing whole lines; it is a separate example from the notification scenario above.

# Blast Radius: checkAdminOrOwner (function, 3 hops)
**Risk Level:** HIGH — wide blast radius, proceed with caution
## Affected Callers (14)
### api/v2
- apps/api/v2/src/modules/atoms/controllers/atoms.conferencing-apps.controller.ts: AtomsConferencingAppsController.listUserInstalledConferencingApps (3 hops)
- apps/api/v2/src/modules/atoms/controllers/atoms.event-types.controller.ts: AtomsEventTypesController.getAtomEventTypeApp (2 hops)
- apps/api/v2/src/modules/atoms/services/conferencing-atom.service.ts: ConferencingAtomsService.getUserConferencingApps (2 hops)
- apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts: EventTypesAtomService.getEventTypesAppIntegration
### app-store/_utils
- packages/app-store/_utils/getConnectedApps.ts: getConnectedApps
### trpc/server
- packages/trpc/server/routers/viewer/apps/integrations.handler.ts: integrationsHandler (2 hops)
- packages/trpc/server/routers/viewer/ooo/outOfOfficeEntriesList.handler.ts: outOfOfficeEntriesList
## Affected Endpoints (2)
- GET /v2/atoms/conferencing
- GET /v2/atoms/event-types-app/:appSlug

That’s enough context to make an intentional change. The agent can update related callers or at least flag the risk before touching the file.

Small detail, big difference.

Why Graph Queries Beat Token-Hungry Code Exploration

How much context an answer needs depends on the question and the repository. In the cal.diy change-impact study, one blast-radius question took a mean of 32.03 seconds with Claude Code's native tools and 16.93 seconds with Pharaoh, over three runs each.

That gap matters every day.

Repeated queries about the same mapped revision give you a shared structure to inspect. The assistant still interprets those results, so check its explanation against the returned paths.

A targeted graph result can narrow the files you inspect next, but it doesn't speed up every question. In the same study, a module overview averaged 22.91 seconds with Pharaoh and 15.12 seconds without it.

If your agent has to rediscover architecture from scratch in every session, your workflow is wasting both tokens and trust.

What a Knowledge Graph for Code Is Not

This helps to say plainly because skepticism here is healthy.

A knowledge graph for code is not:

  • an IDE plugin by definition
  • a coding assistant that writes code for you
  • a code review bot by default
  • a testing tool

It’s a structural intelligence layer. It makes other tools smarter.

That also means it’s different from adjacent categories. Code search platforms help you find files or snippets. Static analysis tools catch rule violations. Security scanners look for risk patterns. Quality frameworks help enforce standards and testing discipline.

Those all matter. They just solve different problems.

A graph helps you understand architecture and relationships. Linting, testing, and standards enforcement belong in a separate layer. If you’re tightening up the broader quality side, AI Codebase Boilerplate, an open-source repo I maintain, is a useful reference.

Where Knowledge Graphs Help Most in Real Developer Workflows

The best use cases are not abstract. They show up in moments where mistakes are expensive and time is short.

Starting in an unfamiliar repo is the obvious one. You need module layout, dependency shape, and hot spots fast.

Before writing new code, search for an existing implementation. A name match is a starting point; inspect the implementation before deciding to reuse it.

Before a refactor, blast radius is the whole game. We’d rather know the risky edges up front than read about them in a bug report later.

After implementation, reachability checks are underrated. New code that isn’t connected to a real entry point is just a well-formatted dead end.

During PR review, structural risk often matters more than line-level style. A tiny diff can have ugly downstream effects.

During cleanup, graphs help identify unused exports for review. In monorepo planning, module dependencies help you inspect which packages are connected.

For a one-to-five-person team, that’s the point. You don’t have margin for avoidable architecture mistakes.

How MCP Changes the Way AI Agents Use Code Context

MCP is basically a standard way for AI tools to call external tools for context and actions. Practical, not mystical.

For code knowledge graphs, that changes the delivery model. The graph doesn’t live in a dashboard you check manually. It becomes available inside the coding session itself.

That’s the big shift.

In tools like Claude Code, Cursor, and Devin Desktop, an agent can query structure before making a change instead of reading random files until it feels confident. That’s a better workflow because the confidence is earned, not guessed.

Pharaoh is one implementation of this pattern. It exposes codebase intelligence through MCP so agents can ask structural questions directly while you work. If you already use an AI coding tool daily, adding this layer is less about changing your stack and more about fixing a missing input.

When a Knowledge Graph Is Worth the Complexity

Not every repo needs this on day one. A tiny throwaway script probably doesn’t.

It starts paying off when a few conditions show up together:

  • the codebase is an active product, not a short-lived prototype
  • your team uses AI agents daily
  • module sprawl is growing
  • refactors carry real regression risk
  • people keep asking “what depends on this?”

A lower-priority case is a very small repo with shallow dependency depth and little reuse. In that world, the setup cost may not justify itself yet.

A simple test works well here. Count how often these happen in a month:

  • duplicate logic appears
  • AI-generated changes miss existing patterns
  • someone asks whether a change is reachable in production
  • a regression comes from misunderstood dependencies

If that count is non-trivial, the graph is probably worth it. The more interconnected the repo gets, the more useful it becomes.

How Pharaoh Applies This Idea in Practice

We built Pharaoh for this exact gap: AI agents are good at local edits and weak at repo-wide structure.

It converts repos into a queryable knowledge graph, parses TypeScript, JavaScript, Python, C and C++ with Tree-sitter, maps functions, modules, dependencies, endpoints, cron jobs, and environment variables, and exposes graph-backed tools through MCP.

The useful tools line up with the questions teams already ask:

  • get_codebase_map: module layout, dependencies and endpoints
  • get_module_context: exports and module relationships
  • search_functions: implementations with signatures and locations
  • get_blast_radius: callers and affected entry points
  • get_unused_code: dead code detection and reachability
  • pharaoh_recon: several structural questions in one call
  • pharaoh_account: account status, live repository and refresh actions

get_module_context returns exported signatures and imports, with callers from other modules, endpoints, cron jobs and environment variable names. The graph stores metadata rather than source-file bodies.

get_codebase_map provides a starting overview of the mapped repository. Follow it with a query about the module or function you intend to change.

Common Objections and the Right Way to Think About Them

The objections are reasonable.

“I can already grep the repo.”
Sure, but grep finds text. It does not tell you transitive impact or production reachability.

“My assistant already reads files.”
Reading files is not the same as understanding relationships across the system. Plenty of bad changes come from agents that read a lot and still miss the important path.

“This sounds like overkill.”
For tiny repos, maybe. For real products, mapping structure once is often cheaper than repeating blind edits all month.

“Isn’t this just another AI layer?”
Not if the answers come from parsed structure and deterministic traversal rather than fresh generation every time.

“Static analysis tools already exist.”
Yes, and they’re useful. But line-level rule checking and architectural graph traversal solve different problems. Don’t ask one tool category to do the other’s job.

Practical Adoption Checklist for an AI-Native Team

If you want to test this without turning it into a platform project, keep it narrow.

  1. Pick the repo where AI mistakes are most expensive.
  2. Write down the recurring questions grep answers poorly:
    • what depends on this
    • does this already exist
    • is this reachable
  3. Add a structural context layer before your next refactor or PR review.
  4. Test it in one workflow first:
    • refactoring sprint
    • PR review
    • new feature wiring check
  5. Pair structural intelligence with tests and quality checks. Don’t treat it as a replacement.

To try this with Pharaoh, install its GitHub App on the account or organization that owns the repositories, then connect your AI client. In a Claude Code terminal, run:

npx @pharaoh-so/mcp

Connect a repository and client.

The mindset shift is the real win: stop asking your agent to infer architecture from scratch every session.

The deterministic graph described here is a structural map. Use it to inspect callers and entry points before changing code, then check the behavior in source and tests.

Better code decisions come from better structure, not better prompting alone.

Pick one active repo. Write down three architecture questions your agent struggles to answer today. Then test whether a graph-backed workflow can answer them before the next refactor or PR review.

Article Record

Update HistoryMeaningful revisions to this article
Added a Video to the Guide
  • Added a YouTube video to provide a helpful visual explanation of knowledge graphs for code.
Initial publication.

More in Code Knowledge Graphs

← Back to blog