Skip to main content
Glama
SGraph MCP Server

SGraph MCP Server

Official
by softagram

SGraph MCP Server

Python 3.13+ License: MIT CI

An MCP server that gives AI agents instant access to software architecture, dependencies, and impact analysis through pre-computed sgraph models. One tool call replaces dozens of grep/read cycles.

Why?

AI agents discover code structure by reading files one at a time. For a question like "what calls this function?", that means grep, read, grep again, read again... Dozens of round-trips, thousands of tokens, and results that still miss indirect callers.

SGraph pre-computes the full dependency graph. The same question takes one call and returns every caller with type information.

Traditional (grep/read)

SGraph MCP

"What calls this function?"

Multiple grep + read cycles

sgraph_get_element_dependencies

"What breaks if I change this?"

Manual trace, easy to miss

sgraph_analyze_change_impact

"Show module structure"

ls + read + scroll

sgraph_get_element_structure

Time per query

Seconds (many round-trips)

Milliseconds (cached)

Accuracy

Text matching (noisy)

Semantic graph (precise)

Related MCP server: CodeGraph

Quick Start

1. Install

git clone https://github.com/softagram/sgraph-mcp-server.git
cd sgraph-mcp-server
uv sync

2. Start the server

# With Claude Code profile (recommended)
uv run python -m src.server --profile claude-code

# With a startup model (skip the load_model step; parsed on first use, not at startup)
uv run python -m src.server --profile claude-code \
  --auto-load /path/to/model.xml.zip \
  --default-scope /Project/src

3. Connect your AI agent

Create .mcp.json in your project root:

{
  "mcpServers": {
    "sgraph": {
      "command": "uv",
      "args": [
        "run", "--directory", "/path/to/sgraph-mcp-server",
        "python", "-m", "src.server",
        "--profile", "claude-code",
        "--transport", "stdio",
        "--auto-load", "/path/to/model.xml.zip"
      ]
    }
  }
}

Stdio is the recommended transport for local use — no port, no bridge, direct IPC. SSE is available for clients that can only speak HTTP or when you want to share one long-running server across multiple clients.

Start the server in SSE mode:

uv run python -m src.server --profile claude-code --transport sse --port 8008

Then connect any MCP client via the mcp-remote bridge:

{
  "mcpServers": {
    "sgraph": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "http://localhost:8008/sse"]
    }
  }
}

sgraph models (.xml.zip files) are produced by Softagram code analysis or the open-source sgraph CLI tools.

The models represent your codebase as a hierarchical graph:

/Project
  /Project/src
    /Project/src/auth/login.py
      /Project/src/auth/login.py/LoginHandler        (class)
        /Project/src/auth/login.py/LoginHandler/validate  (method)
  /Project/External
    /Project/External/Python/requests                 (third-party)

Each element can have associations (dependencies) to other elements, forming a complete dependency graph.

Tools

The claude-code profile provides 6 tools optimized for AI-assisted development:

Tool

What it does

When to use

sgraph_search_elements

Find symbols by pattern

"Where is the UserService class?"

sgraph_get_element_dependencies

Query incoming/outgoing deps

"What calls this function?"

sgraph_get_element_structure

Explore hierarchy

"What's inside this module?"

sgraph_analyze_change_impact

Multi-level impact analysis

"What breaks if I change this?"

sgraph_audit

Architectural health checks

"Any circular dependencies?"

sgraph_security_audit

Security posture overview

"Any exposed secrets or CVEs?"

The key tool is sgraph_get_element_dependencies with its result_level parameter for controlling abstraction:

result_level=None  ->  /Project/src/auth/login.py/LoginHandler/validate  (raw)
result_level=4     ->  /Project/src/auth/login.py                        (file)
result_level=3     ->  /Project/src/auth                                 (directory)
result_level=2     ->  /Project/src                                      (component)

For the full tool reference with workflows and examples, see SGRAPH_FOR_CLAUDE_CODE.md.

The legacy profile provides the full original tool set for backwards compatibility:

Basic Operations: sgraph_load_model, sgraph_get_root_element, sgraph_get_element, sgraph_get_element_incoming_associations, sgraph_get_element_outgoing_associations

Search: sgraph_search_elements_by_name, sgraph_get_elements_by_type, sgraph_search_elements_by_attributes

Analysis: sgraph_get_subtree_dependencies, sgraph_get_dependency_chain, sgraph_get_multiple_elements, sgraph_get_model_overview, sgraph_get_high_level_dependencies

uv run python -m src.server --profile legacy

Example Conversation

You: "What would break if I rename the validate() method in auth/login.py?"

Agent calls: sgraph_analyze_change_impact(element_path="/Project/src/auth/login.py/LoginHandler/validate")

Result:
  5 callers in 3 files
  - /Project/src/api/routes.py (2 call sites)
  - /Project/src/middleware/auth.py (2 call sites)
  - /Project/tests/test_auth.py (1 call site)
  Warning: bidirectional dependency with /Project/src/middleware

Architecture

MCP Client Request
       |
[Tools Layer]     src/tools/        -- MCP tool definitions, input validation
       |
[Services Layer]  src/services/     -- Business logic (search, deps, security)
       |
[Core Layer]      src/core/         -- Model management, data conversion
       |
[SGraph Library]                    -- Graph operations (sgraph package)

See ARCHITECTURE.md for the detailed design.

Development

# Run tests
uv run python tests/run_all_tests.py
uv run python tests/run_all_tests.py unit          # Unit only
uv run python tests/run_all_tests.py integration   # Integration only

# Lint
uv run ruff check src/

# Run a single test file
uv run python -m pytest tests/unit/test_collect_deps.py -v

See CONTRIBUTING.md for how to contribute.

About

Built by Softagram using the open-source sgraph library. Licensed under MIT.

Available Tools

11 tools
sgraph_analyze_change_impactA

BEFORE modifying any public interface, call this to see what breaks.

Returns ALL abstraction levels at once (no need for multiple calls):

  • detailed: Every function/method that uses this element

  • by_file: Which files would need changes

  • by_module: Which modules/repos are affected

Automatic warnings (when detected):

  • dependency_cycle: bidirectional module deps — blast radius exceeds listed callers

  • hub_element: >30 outgoing deps — changes cascade widely

When to use:

  • Before changing function signature -> see all call sites

  • Before renaming class -> see all importers

  • Before deleting code -> verify nothing depends on it

  • Planning large refactoring -> understand blast radius

Returns JSON with summary, warnings, and callers at multiple aggregation levels.

Inputs: input (required).

sgraph_auditA

Run architectural health checks on the codebase. For occasional reviews, not daily use.

Available checks:

  • "cycles": Find circular module dependencies (A depends on B, B depends on A)

  • "hubs": Find modules with unusually high coupling (many dependencies)

aggregation_level controls module granularity:

  • 2: /project/component (coarse, good for monorepos)

  • 3: /project/component/module (default)

  • 4+: deeper nesting for fine-grained analysis

Returns JSON with cycles, hub modules, and summary metrics.

Inputs: input (required).

sgraph_cypher_queryA

Run an openCypher query against the loaded model. Powerful and flexible.

Use this tool for complex graph queries that the other tools can't express:

  • Multi-hop path queries, transitive dependencies

  • Aggregation (count, group by)

  • Complex filtering with AND/OR/NOT

  • Joining different relationship types

The sgraph model is mapped to a labeled property graph:

Nodes (= code elements):

  • Labels come from element type: :file, :class, :function, :dir, :method, etc.

  • Properties: name, path (always present), plus all element attributes

  • Elements without a type have no label

Relationships (= dependencies):

  • Type comes from deptype: :imports, :function_ref, :call, :inc, :uses, etc.

  • Properties: any edge-level attributes

  • :CONTAINS relationships represent parent-child hierarchy (off by default)

Example queries:

"What files does main.py import?" MATCH (a:file)-[:imports]->(b:file) WHERE a.name = 'main.py' RETURN b.name, b.path

"Count dependencies per file, top 10:" MATCH (a:file)-[r]->(b) WHERE type(r) <> 'CONTAINS' RETURN a.name, count(r) AS deps ORDER BY deps DESC LIMIT 10

"Find all transitive imports from a file (up to 3 hops):" MATCH (a:file)-[:imports*1..3]->(b) WHERE a.name = 'app.py' RETURN DISTINCT b.name, b.path

"Files with more than 500 lines of code:" MATCH (f:file) WHERE f.loc > 500 RETURN f.name, f.loc ORDER BY f.loc DESC

"Does module A depend on module B? (directory-level)" MATCH (a)-[r]->(b) WHERE a.path STARTS WITH '/project/src/web/' AND b.path STARTS WITH '/project/src/db/' AND type(r) <> 'CONTAINS' RETURN type(r), count(r) AS cnt ORDER BY cnt DESC

Performance notes:

  • include_hierarchy=false (default) is faster, omits :CONTAINS edges

  • Enable include_hierarchy only for parent-child traversal queries

  • Large models take a few seconds for initial indexing (cached per model)

  • Variable-length paths (*1..N) with large N can be slow

Returns JSON array of result rows. Read-only: CREATE/DELETE/SET not supported.

Inputs: input (required).

sgraph_get_element_attributesA

Get all attributes (metadata) of a code element.

When to use:

  • Check quality metrics (loc, risk_density, softagram_index)

  • Check ownership info (backstage metadata, author counts)

  • See security markers (secret_type, severity, outdated)

  • Inspect any element metadata before deeper analysis

Returns element info + all attributes as flat key-value pairs. Only attributes that exist on the element are included.

Inputs: input (required).

sgraph_get_element_dependenciesA

Query what code depends on an element, or what it depends on. THE KEY TOOL.

When to use:

  • Before modifying a function: check incoming (what calls this?)

  • Understanding a class: check outgoing (what does it use?)

  • Planning refactoring: check both directions

  • Check module-level dependency: "does src/web depend on src/db?"

Direction:

  • "incoming": What uses THIS element (callers, importers) - for impact analysis

  • "outgoing": What THIS element uses (callees, imports) - for understanding context

  • "both": Both directions in one call

result_level (controls abstraction):

  • None: Raw dependencies (function->function) - for precise call sites

  • 4: File level - "which files depend on this?"

  • 3: Directory level - "which directories depend on this?"

  • 2: Repository level - "which repos depend on this?"

include_descendants:

  • false (default): Only this element's own dependencies

  • true: Also include children's dependencies. Relative paths (no leading /) show which descendant: "MyClass/Save -> /target (call)"

target_filter:

  • Optional path prefix to filter results. Only dependencies whose target (outgoing) or source (incoming) starts with this prefix are returned.

  • Example: target_filter="/project/src/db" with direction="outgoing" answers "does this module depend on src/db?"

WARNING: include_descendants=true on large directories (e.g., src/) can return thousands of results. Use target_filter or result_level=3 to keep output manageable.

Example - "Does src/web depend on src/db?": element_path="/project/src/web", direction="outgoing", include_descendants=true, result_level=3, target_filter="/project/src/db" -> Returns only dependencies from src/web subtree targeting src/db

Returns JSON with outgoing/incoming dependency lists.

Inputs: input (required).

sgraph_get_element_structureA

Explore what's inside a file, class, or directory WITHOUT reading source code.

When to use:

  • See what classes/functions a file contains (instead of Read + scroll)

  • Explore a directory structure (instead of ls + recursive exploration)

  • Understand class methods before diving into implementation

max_depth:

  • 1: Direct children only (file->classes, dir->files)

  • 2: Two levels (file->classes->methods) - usually sufficient

  • 3+: Deeper nesting (rarely needed)

Returns JSON hierarchy with path, type, name, and children. Much cheaper than Read - use this first to decide what to read.

Inputs: input (required).

sgraph_load_modelA

Load a graph model from file and return its ID for subsequent queries. If the model was already auto-loaded at startup, returns the existing ID instantly.

Inputs: input (required).

sgraph_queryA

Filter the model using SGraph Query Language — concise, architecture-native syntax.

Best for: filtering sub-models, checking module dependencies, attribute-based element selection. Returns a filtered model (elements + associations), not tabular data. For tabular queries and aggregation, use sgraph_cypher_query instead.

Syntax quick reference:

Element selection: "/project/src/web" Exact path (quoted, case-sensitive) phone Keyword (unquoted, case-insensitive partial match) "/path/*" Direct children "/path/**" All descendants

Attribute filters: @type=file Attribute equals (contains match) @type="file" Exact match (quoted value) @type!=dir Not equals @loc>500 Greater than (numeric) @loc<100 Less than @name=~".*.py$" Regex match @loc Has attribute (any value)

Dependency queries: "/src/web" --> "/src/db" Directed: does web depend on db? "/src/web" -- "/src/db" Undirected: dependency in either direction "/web" -import-> "/db" Filter by dependency type "*" --> "/src/db" Wildcard: anything that depends on db "/a" ---> "/b" Chain search: all transitive paths (DFS) "/a" --import-> "/b" Chain with type filter "/a" --- "/b" Shortest undirected path (BFS)

Logical operators: expr1 AND expr2 Sequential filter (intersection) expr1 OR expr2 Union NOT expr Complement (expr) Grouping

Examples: @type=file AND @loc>500 "/src" AND NOT "/src/External" "/src/web" --> "/src/db" (@type=file OR @type=dir) AND @loc>200

Returns JSON with elements (path, type, name) and associations (from, to, type).

Inputs: input (required).

sgraph_resolve_local_pathA

Map sgraph path to local filesystem path. Use to find source code for NuGet packages.

When to use:

  • You found a class/method in sgraph and need to read its source code

  • You want to understand what a NuGet package method does internally

  • You need to navigate from dependency analysis to actual code

The mapping is configured in sgraph-mapping.json. Default maps:

  • /Organization///... -> /mnt/c/code//...

Returns:

  • sgraph_path: Original path

  • repo_name: Git repository name (3rd level in hierarchy)

  • local_path: Resolved filesystem path

  • exists: Whether the file/dir exists locally

After resolving, use the Read tool to view the source code.

Inputs: input (required).

sgraph_search_elementsA

Find code elements by name pattern. Use instead of grep for precise symbol lookup.

When to use:

  • You know a class/function name but not its file location

  • You want to find all implementations of a pattern (e.g., "Service", "*Handler")

  • You need to locate a symbol before querying its dependencies

Parameters:

  • query: Wildcards ("Service") or regex (".Service.") or substring ("Service")

  • scope_path: Limit to subtree - faster, fewer results. Auto-set if server has default scope.

  • element_types: Filter by ["class", "function", "method", "file", "dir"]

  • model_id: Omit to use auto-loaded model

Returns JSON with match count and element list.

Inputs: input (required).

sgraph_security_auditA

Security overview across 6 dimensions: secrets, vulnerabilities, outdated/EOL, risk levels, backstage metadata, bus factor.

Use for: organizational security posture, audit preparation, risk prioritization.

Dimensions (only those with findings are included):

  • secrets: potential secrets committed to code (API keys, tokens, national IDs)

  • vulnerabilities: CVEs in dependencies, by severity

  • outdated: end-of-life frameworks and approaching-EOL packages

  • risk: code risk density and Softagram Index (0-100, higher=better)

  • backstage: service ownership, lifecycle, public exposure

  • bus_factor: single-author critical files, low-author repositories

Returns JSON with summary + per-dimension breakdown.

Inputs: input (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 11 tools

    Disambiguation4/5

    Each tool has a clearly specialized purpose with explicit 'when to use' guidance, so agents can generally pick the right one. Minor overlap exists between sgraph_query, sgraph_cypher_query, and sgraph_get_element_dependencies, since all can express dependency lookups, but the intended boundaries are described well enough to avoid major confusion.

    Naming Consistency4/5

    All tools share the sgraph_ prefix and snake_case naming, which gives the set a strong sense of consistency. Most names follow a verb_object pattern (load_model, search_elements, get_element_dependencies), but sgraph_audit, sgraph_query, and sgraph_security_audit are slightly less uniform in structure.

    Tool Count5/5

    Eleven tools is a well-scoped size for a code dependency graph analysis server. Each tool covers a distinct aspect of the workflow—loading, searching, exploring, analyzing impact, auditing, and querying—so none feels redundant or excessive.

    Completeness5/5

    The tool surface covers model loading, symbol search, structural exploration, dependency and impact analysis, architecture audits, security audits, attribute inspection, path resolution, and two flexible query languages. The only apparent workflow gap—reading actual source code—is intentionally bridged by resolving local paths and delegating to a Read tool, and advanced needs are covered by sgraph_cypher_query.

    Maintenance

    ActivityStale
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Supercharges AI coding agents with a pre-indexed semantic code graph, enabling instant symbol relationships, impact analysis, and context retrieval across 20+ languages.
      181,132 npm
      78,779
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Supercharges AI coding agents with semantic code intelligence, providing pre-built knowledge graphs for surgical context, faster answers, and fewer tool calls.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to query and analyze code across multiple repositories through a unified knowledge graph, with tools for symbol search, impact analysis, and graph algorithms.
      MIT