# MCP Tools & Context Workflow

> How CodeGraph exposes provider-neutral code intelligence through stdio JSON-RPC tools, why codegraph_context is the primary workflow, and how search, callers, callees, impact, explore, node, status, and files fit together.

- Repository: colbymchenry/codegraph
- GitHub: https://github.com/colbymchenry/codegraph
- Human wiki: https://grok-wiki.com/public/wiki/colbymchenry-codegraph-89e8b2c4d43a
- Complete Markdown: https://grok-wiki.com/public/wiki/colbymchenry-codegraph-89e8b2c4d43a/llms-full.txt

## Source Files

- `src/mcp/index.ts`
- `src/mcp/tools.ts`
- `src/mcp/transport.ts`
- `src/mcp/server-instructions.ts`
- `src/context/index.ts`
- `src/context/formatter.ts`
- `__tests__/mcp-initialize.test.ts`
- `__tests__/mcp-roots.test.ts`

---

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [src/mcp/index.ts](src/mcp/index.ts)
- [src/mcp/tools.ts](src/mcp/tools.ts)
- [src/mcp/transport.ts](src/mcp/transport.ts)
- [src/mcp/server-instructions.ts](src/mcp/server-instructions.ts)
- [src/context/index.ts](src/context/index.ts)
- [src/context/formatter.ts](src/context/formatter.ts)
- [src/index.ts](src/index.ts)
- [src/bin/codegraph.ts](src/bin/codegraph.ts)
- [src/installer/targets/shared.ts](src/installer/targets/shared.ts)
- [src/types.ts](src/types.ts)
- [__tests__/mcp-initialize.test.ts](__tests__/mcp-initialize.test.ts)
- [__tests__/mcp-roots.test.ts](__tests__/mcp-roots.test.ts)
</details>

# MCP Tools & Context Workflow

CodeGraph exposes its indexed code knowledge graph through an MCP server that speaks JSON-RPC 2.0 over stdio. The result is intentionally provider-neutral: any client or agent runtime that can launch `codegraph serve --mcp` and exchange MCP messages over stdin/stdout can use the same local graph, without assuming a specific model vendor, hosted service, or proprietary connector.

This page explains the runtime handshake, why `codegraph_context` is the primary workflow, and how the supporting tools fit together when an agent needs search, call graph tracing, blast-radius analysis, source inspection, status, or indexed file structure.

Sources: [src/mcp/transport.ts:1-5](), [src/bin/codegraph.ts:1101-1121](), [src/installer/targets/shared.ts:14-24](), [src/mcp/server-instructions.ts:1-7]()

## Runtime Boundary

At runtime, `MCPServer` owns the stdio transport, a default `CodeGraph` instance when one is resolved, and a `ToolHandler` that executes individual `codegraph_*` tools. The server starts listening immediately, handles process shutdown signals, and defers project initialization until it has enough client context to choose the right workspace root.

```text
MCP client / agent
        |
        | JSON-RPC 2.0 over stdio
        v
src/mcp/transport.ts
        |
        v
src/mcp/index.ts  ->  ToolHandler in src/mcp/tools.ts
        |                         |
        v                         v
CodeGraph instance           context/search/call/status/file handlers
        |
        v
SQLite-backed local code graph
```

The server’s routing surface is small: `initialize`, `initialized`, `tools/list`, `tools/call`, and `ping` are the recognized JSON-RPC methods. Unknown request methods get a standard method-not-found error.

Sources: [src/mcp/index.ts:83-104](), [src/mcp/index.ts:112-125](), [src/mcp/index.ts:300-343](), [src/mcp/transport.ts:47-56]()

## Initialization And Root Resolution

The initialize response is deliberately sent before heavy CodeGraph initialization. The implementation comments call out slow filesystem and tree-sitter WASM startup cases where blocking the handshake caused MCP tools not to appear in clients. After responding, the server initializes in the background when it has an explicit path.

Project root selection is ordered by strength of signal:

| Signal | When Used | Behavior |
|---|---|---|
| `rootUri` | Client sends it during `initialize` | Converted from `file://` URI to a filesystem path. |
| `workspaceFolders[0].uri` | Client sends workspace folders | First folder is used. |
| `--path` constructor argument | Server was launched with a path | Used as the explicit project path. |
| `roots/list` | No explicit path, client advertised `roots` | Server asks the client for workspace roots on first needed tool call. |
| `process.cwd()` | Last resort | Used only after no stronger project signal is available. |

The `roots/list` path matters for BYOC/BYOK and editor portability: clients can launch the same stdio server from outside the repository while still reporting the real workspace root through MCP, instead of relying on a vendor-specific launch directory convention.

Sources: [src/mcp/index.ts:348-407](), [src/mcp/index.ts:171-216](), [src/mcp/index.ts:218-238](), [__tests__/mcp-roots.test.ts:1-17]()

```mermaid
sequenceDiagram
    participant Client as MCP client
    participant Server as MCPServer
    participant Transport as StdioTransport
    participant Graph as CodeGraph

    Client->>Server: initialize(rootUri? workspaceFolders? roots?)
    Server-->>Client: initialize result with tools capability and instructions
    alt explicit rootUri/workspaceFolders/--path
        Server->>Graph: tryInitializeDefault(explicitPath) in background
    else roots capability but no explicit path
        Client->>Server: tools/call
        Server->>Transport: roots/list
        Transport-->>Server: first file:// root
        Server->>Graph: tryInitializeDefault(root)
    else no usable root signal
        Server->>Graph: tryInitializeDefault(process.cwd())
    end
```

The tests enforce both contracts: initialize must respond quickly even when no `.codegraph` exists, and when a real `.codegraph` exists the initialize JSON-RPC response must be observed before watcher startup logs prove initialization finished.

Sources: [__tests__/mcp-initialize.test.ts:1-12](), [__tests__/mcp-initialize.test.ts:110-148](), [__tests__/mcp-roots.test.ts:96-126](), [__tests__/mcp-roots.test.ts:153-179]()

## Transport: Plain JSON-RPC Over Stdio

`StdioTransport` reads one JSON-RPC message per stdin line and writes JSON responses or notifications to stdout. It also supports server-initiated requests, which CodeGraph uses for `roots/list`; pending requests are keyed by generated IDs and rejected on timeout so the server can fall back instead of hanging.

Short excerpt from `src/mcp/transport.ts`:

```ts
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
```

This boundary is intentionally simple. It keeps CodeGraph portable across local agent clients and skill/catalog sources: the server is just a local process with stdio, and model/provider choice stays outside the repository.

Sources: [src/mcp/transport.ts:63-72](), [src/mcp/transport.ts:77-93](), [src/mcp/transport.ts:110-133](), [src/mcp/transport.ts:177-226]()

## Why `codegraph_context` Is The Primary Workflow

The tool definitions and server instructions both steer agents toward `codegraph_context` first for “how does this work?”, architecture, feature-area, and bug-context questions. The reason is visible in the context builder: it turns a natural-language task into a compact markdown context by finding entry points, expanding graph relationships, extracting key code blocks, collecting related files, and computing stats in one call.

That makes `codegraph_context` the default first move for understanding a code area. It is not a replacement for product clarification: the tool handler adds a reminder for feature-like tasks because code context does not define UX preferences, edge cases, or acceptance criteria.

Sources: [src/mcp/tools.ts:241-276](), [src/mcp/server-instructions.ts:25-35](), [src/context/index.ts:196-267](), [src/mcp/tools.ts:640-675]()

### What Context Contains

`TaskContext` stores the original query, relevant subgraph, entry points, code blocks, related files, summary, and basic stats. The markdown formatter emits a compact document with entry points, related symbols grouped by file, and selected code blocks.

Sources: [src/types.ts:746-818](), [src/context/formatter.ts:9-71]()

## Tool Map

| Tool | Use It For | Implementation Notes |
|---|---|---|
| `codegraph_context` | First-pass task, architecture, feature-area, or bug context | Builds markdown context through `cg.buildContext()`. |
| `codegraph_search` | Quick symbol lookup by name | Returns locations and signatures, not source bodies. |
| `codegraph_callers` | “What calls this?” | Aggregates callers across all exact matching symbols. |
| `codegraph_callees` | “What does this call?” | Aggregates callees across all exact matching symbols. |
| `codegraph_impact` | Blast radius for a symbol change | Merges impact subgraphs across matching symbols. |
| `codegraph_explore` | Source for several related symbols | Groups symbols by file, shows relationships, and caps output adaptively. |
| `codegraph_node` | One symbol’s details | Defaults to no source; container nodes return outlines when source is requested. |
| `codegraph_status` | Index health and size | Reports files, nodes, edges, DB size, backend, node kinds, languages. |
| `codegraph_files` | Indexed file structure | Returns tree, flat, or grouped views with optional metadata. |

Sources: [src/mcp/tools.ts:248-442](), [src/mcp/tools.ts:585-612](), [src/mcp/tools.ts:617-637](), [src/mcp/tools.ts:1270-1353](), [src/mcp/tools.ts:1355-1404]()

## Context Workflow For A Reader Or Agent

For the first 30 minutes in a repo, use tools by intent rather than by implementation curiosity:

1. Start with `codegraph_context` for the task or area.
2. If you need source for several surfaced symbols, use one `codegraph_explore` with specific symbol, file, or code terms.
3. If one symbol needs exact details, use `codegraph_node`.
4. For refactors, use `codegraph_search`, then `codegraph_callers`, then `codegraph_impact`.
5. For project shape, use `codegraph_files`; for index health, use `codegraph_status`.

This mirrors the server-level playbook emitted in the initialize response. It also avoids repeated search/read loops that duplicate the graph index’s job.

Sources: [src/mcp/server-instructions.ts:37-60](), [src/mcp/index.ts:373-391](), [src/mcp/tools.ts:380-398]()

## How `codegraph_explore` Fits After Context

`codegraph_explore` is a breadth tool, but it is not the first tool for natural-language questions. Its description asks callers to query with specific symbol, file, or code terms, and its handler uses `findRelevantContext()` with larger search/traversal budgets before grouping results by file.

The output is intentionally capped and shaped. It scores files around entry points, can include a relationship map, reads contiguous source sections, clusters nearby symbol ranges, includes line numbers by default, and adds “additional relevant files” or budget notes depending on project size.

Sources: [src/mcp/tools.ts:380-398](), [src/mcp/tools.ts:819-858](), [src/mcp/tools.ts:863-932](), [src/mcp/tools.ts:994-1093](), [src/mcp/tools.ts:1207-1268]()

## Symbol Resolution And Ambiguity

The handler supports simple symbol names and qualified names using dot, slash, or `::` separators. For qualified lookups, it can suffix-match `qualifiedName` or match path segments, which helps languages where module/package structure is represented in file paths. `callers`, `callees`, and `impact` use the “all symbols” path so ambiguous names aggregate across exact matches and include a note about the matched locations.

Sources: [src/mcp/tools.ts:1547-1604](), [src/mcp/tools.ts:1606-1648](), [src/mcp/tools.ts:1650-1681](), [src/mcp/tools.ts:706-817]()

## Status, Files, And Freshness

`codegraph_status` reads graph stats and backend state from the active `CodeGraph` connection. `codegraph_files` reads the indexed file list, filters by path or glob-like pattern, and can render tree, flat, or language-grouped output. These tools use the index, not a live filesystem scan.

Freshness is handled by the MCP server starting the CodeGraph watcher when available. If watching is disabled or unavailable, the server writes a diagnostic message telling the user to run `codegraph sync` or use git sync hooks.

Sources: [src/index.ts:606-623](), [src/index.ts:686-690](), [src/mcp/tools.ts:1308-1353](), [src/mcp/tools.ts:1355-1404](), [src/mcp/index.ts:240-280]()

## Internal API Boundary

The MCP layer is a wrapper over `CodeGraph` methods rather than a separate intelligence engine. `CodeGraph` exposes node search, file listing, call graph traversal, callers, callees, impact radius, source extraction, `findRelevantContext()`, and `buildContext()`. The MCP tools choose argument defaults, output shape, truncation, cross-project lookup, and agent-facing descriptions.

Sources: [src/index.ts:650-655](), [src/index.ts:711-723](), [src/index.ts:725-798](), [src/index.ts:896-943](), [src/mcp/tools.ts:444-560]()

## Portable Integration Notes

The installed MCP config helper emits the same local stdio command shape for JSON-shaped agent configs: `type: "stdio"`, `command: "codegraph"`, and `args: ["serve", "--mcp"]`. Codex TOML has its own wrapper, but the underlying local command remains the same. This is the key portability point for Grok-Wiki or other BYOC/BYOK integrations: integration code should depend on local MCP process configuration and repository/cached skill files, not on a specific hosted model or connector.

The selected wiki knowledge profile also requested strategy and solved-problem sources. This checkout did not contain `STRATEGY.md` or `docs/solutions/**`, so implementation claims in this page are grounded in repository code and regression tests.

Sources: [src/installer/targets/shared.ts:14-24](), [src/bin/codegraph.ts:1101-1121](), [src/mcp/server-instructions.ts:1-17]()

## Summary

The MCP workflow is: launch a local stdio server, resolve the project root through explicit client signals or MCP roots, expose a compact set of graph-backed tools, and steer agents toward `codegraph_context` before narrower follow-up calls. `search`, `callers`, `callees`, `impact`, `explore`, `node`, `status`, and `files` are supporting tools around that primary context-building loop, each backed by the same local CodeGraph index rather than provider-specific code intelligence.

Sources: [src/mcp/tools.ts:241-248](), [src/context/index.ts:270-283](), [src/index.ts:925-943]()
