Analyze Codebase for MCP
Scan codebase → fns, REST endpoints, CLI cmds, data access candidates → MCP tool exposure → structured tool spec doc.
Use When
- Plan MCP server existing project → know what to expose
- Audit codebase pre-AI-tool-surface wrap
- Compare codebase capability vs MCP exposed
- Generate tool spec → hand to
scaffold-mcp-server
- Evaluate 3rd-party lib worth wrapping
In
- Required: Path to codebase root
- Required: Target lang(s) (TS, Python, R, Go)
- Optional: Existing MCP server code → gap analysis
- Optional: Domain focus ("data analysis", "file ops", "API integration")
- Optional: Max tools to recommend (default: 20)
Do
Step 1: Scan Structure
1.1. Glob → dir tree, src dirs:
src/**/*.{ts,js,py,R,go,rs} → src files
**/routes/**, **/api/**, **/controllers/** → endpoints
**/cli/**, **/commands/** → CLI entries
**/package.json, **/setup.py, **/DESCRIPTION → dep metadata
1.2. Categorize by role:
- Entry: main files, route handlers, CLI cmds
- Core logic: business fns, algos, data transformers
- Data access: DB queries, file I/O, API clients
- Utilities: helpers, formatters, validators
1.3. Count files, LOC, exported symbols → gauge size.
→ Categorized inventory w/ role annotations.
If err: Too large (>10K files) → narrow via domain focus. No src found → verify root path + lang params.
Step 2: Identify Fns + Endpoints
2.1. Grep exported fns + public APIs:
- TS/JS:
export (async )?function, export default, module.exports
- Python: fns no
_ prefix, @app.route, @router
- R: NAMESPACE or
#' @export roxygen
- Go: capitalized fn names (exported by convention)
2.2. Per candidate extract:
- Name: fn/endpoint
- Signature: params w/ types + defaults
- Return type
- Docs: docstrings, JSDoc, roxygen, godoc
- Location: file path + line
2.3. REST APIs, also extract:
- HTTP method + route pattern
- Req body schema
- Res shape
- Auth reqs
2.4. Sort by potential utility (public, documented, well-typed first).
→ 20-100 candidates w/ extracted metadata.
If err: Few candidates → broaden → include internal that could be public. Sparse docs → flag as risk.
Step 3: Evaluate MCP Suitability
3.1. Per candidate → MCP tool criteria:
- In contract clarity: params well-typed + documented? JSON Schema describable?
- Out predictability: structured (JSON-serializable)? Consistent shape?
- Side effects: modifies state (files, DB, external)? Must be labeled.
- Idempotency: safe to retry? Non-idempotent → explicit warn.
- Exec time: completes <30s? Long-running → async patterns.
- Err handling: structured errs or silent fail?
3.2. Score 1-5:
- 5: Pure fn, typed I/O, documented, fast, no side effects
- 4: Well-typed, documented, minor side effects (logging)
- 3: Reasonable I/O, needs wrapping (raw objects)
- 2: Significant side effects or unclear, substantial adaptation
- 1: Not suitable no major refactor
3.3. Filter ≥3. Flag score-2 → "future candidates" needing refactor.
→ Scored + filtered list w/ suitability rationale.
If err: Most <3 → codebase needs refactor pre-MCP. Doc gaps → recommend (add types, extract pure fns, wrap side effects).
Step 4: Design Tool Specs
4.1. Per selected (≥3) draft spec:
- name: tool_name
description: >
One-line description of what the tool does.
source_function: module.function_name
source_file: src/path/to/file.ts:42
parameters:
param_name:
type: string | number | boolean | object | array
description: What this parameter controls
required: true | false
default: value_if_optional
returns:
type: string | object | array
description: What the tool returns
side_effects:
- description of any side effect
estimated_latency: fast | medium | slow
suitability_score: 5
4.2. Group logical categories ("Data Queries", "File Ops", "Analysis", "Config").
4.3. Identify deps between tools ("list_datasets" before "query_dataset").
4.4. Need wrappers?
- Simplify complex param objects → flat in
- Convert raw returns → structured text/JSON
- Safety guards (read-only wrappers for DB fns)
→ Complete YAML spec w/ categories, deps, wrapper notes.
If err: Ambiguous → Step 2 → more src detail. Param types uninferable → flag manual review.
Step 5: Generate Tool Spec Doc
5.1. Final doc sections:
- Summary: Codebase overview, lang, size, date
- Recommended Tools: Full specs from Step 4, grouped
- Future Candidates: Score-2 + refactor recs
- Excluded: Score-1 + rationale
- Dependencies: Tool dep graph
- Impl Notes: Wrappers, auth, transport
5.2. Save mcp-tool-spec.yml (machine) + mcp-tool-spec.md (human).
5.3. Existing MCP server provided → gap analysis:
- In spec, not impl
- Impl, not in spec (stale)
- Spec drift (impl diverges)
→ Complete doc → consumable by scaffold-mcp-server.
If err: >200 tools → split modules w/ cross-refs. No candidates → "readiness assessment" doc w/ refactor recs.
Check
Traps
- Too many tools: AI works best 10-30 focused. Breadth > depth. Resist every public fn.
- Ignore side effects: "Just reads" + logs/cache = still side effects. Audit
Grep file writes, network, DB.
- Assume type safety: Dynamic langs (Py, R, JS) may lack type annotations. Infer from usage, flag uncertainty.
- Missing auth ctx: Fns working in authed web req may fail via MCP no session. Check implicit session cookies, JWT, env creds.
- Over-engineer wrappers: 50-line wrapper → not good candidate. Prefer natural mapping.
- Neglect err paths: MCP must return structured errs. Untyped exceptions → err-handling wrappers.
- Conflate internal + external APIs: Internal helpers poor candidates. Focus external-consumption or boundary APIs.
- Skip gap analysis: Existing MCP provided → always compare. No gap analysis → duplicate work or stale tools.
→
scaffold-mcp-server — use out spec → working MCP
build-custom-mcp-server — manual impl ref
configure-mcp-server — connect to Claude Code/Desktop
troubleshoot-mcp-connection — debug after deploy
review-software-architecture — arch review for tool surface
security-audit-codebase — audit pre-external exposure
1---2name: analyze-codebase-for-mcp-103description: Analyze an arbitrary codebase to identify functions, APIs, and data sources suitable for exposure as MCP tools, producing a tool specification document. Use when planning an MCP server for an existing project, auditing a codebase before wrapping it as an AI-accessible tool surface, comparing what a codebase can do versus what is already exposed via MCP, or generating a tool spec to hand off to scaffold-mcp-server.4license: MIT5---67# Analyze Codebase for MCP89Scan codebase → fns, REST endpoints, CLI cmds, data access candidates → MCP tool exposure → structured tool spec doc.1011## Use When1213- Plan MCP server existing project → know what to expose14- Audit codebase pre-AI-tool-surface wrap15- Compare codebase capability vs MCP exposed16- Generate tool spec → hand to `scaffold-mcp-server`17- Evaluate 3rd-party lib worth wrapping1819## In2021- **Required**: Path to codebase root22- **Required**: Target lang(s) (TS, Python, R, Go)23- **Optional**: Existing MCP server code → gap analysis24- **Optional**: Domain focus ("data analysis", "file ops", "API integration")25- **Optional**: Max tools to recommend (default: 20)2627## Do2829### Step 1: Scan Structure30311.1. `Glob` → dir tree, src dirs:32 - `src/**/*.{ts,js,py,R,go,rs}` → src files33 - `**/routes/**`, `**/api/**`, `**/controllers/**` → endpoints34 - `**/cli/**`, `**/commands/**` → CLI entries35 - `**/package.json`, `**/setup.py`, `**/DESCRIPTION` → dep metadata36371.2. Categorize by role:38 - **Entry**: main files, route handlers, CLI cmds39 - **Core logic**: business fns, algos, data transformers40 - **Data access**: DB queries, file I/O, API clients41 - **Utilities**: helpers, formatters, validators42431.3. Count files, LOC, exported symbols → gauge size.4445**→** Categorized inventory w/ role annotations.4647**If err:** Too large (>10K files) → narrow via domain focus. No src found → verify root path + lang params.4849### Step 2: Identify Fns + Endpoints50512.1. `Grep` exported fns + public APIs:52 - TS/JS: `export (async )?function`, `export default`, `module.exports`53 - Python: fns no `_` prefix, `@app.route`, `@router`54 - R: NAMESPACE or `#' @export` roxygen55 - Go: capitalized fn names (exported by convention)56572.2. Per candidate extract:58 - **Name**: fn/endpoint59 - **Signature**: params w/ types + defaults60 - **Return type**61 - **Docs**: docstrings, JSDoc, roxygen, godoc62 - **Location**: file path + line63642.3. REST APIs, also extract:65 - HTTP method + route pattern66 - Req body schema67 - Res shape68 - Auth reqs69702.4. Sort by potential utility (public, documented, well-typed first).7172**→** 20-100 candidates w/ extracted metadata.7374**If err:** Few candidates → broaden → include internal that could be public. Sparse docs → flag as risk.7576### Step 3: Evaluate MCP Suitability77783.1. Per candidate → MCP tool criteria:7980 - **In contract clarity**: params well-typed + documented? JSON Schema describable?81 - **Out predictability**: structured (JSON-serializable)? Consistent shape?82 - **Side effects**: modifies state (files, DB, external)? Must be labeled.83 - **Idempotency**: safe to retry? Non-idempotent → explicit warn.84 - **Exec time**: completes <30s? Long-running → async patterns.85 - **Err handling**: structured errs or silent fail?86873.2. Score 1-5:88 - **5**: Pure fn, typed I/O, documented, fast, no side effects89 - **4**: Well-typed, documented, minor side effects (logging)90 - **3**: Reasonable I/O, needs wrapping (raw objects)91 - **2**: Significant side effects or unclear, substantial adaptation92 - **1**: Not suitable no major refactor93943.3. Filter ≥3. Flag score-2 → "future candidates" needing refactor.9596**→** Scored + filtered list w/ suitability rationale.9798**If err:** Most <3 → codebase needs refactor pre-MCP. Doc gaps → recommend (add types, extract pure fns, wrap side effects).99100### Step 4: Design Tool Specs1011024.1. Per selected (≥3) draft spec:103104```yaml105- name: tool_name106 description: >107 One-line description of what the tool does.108 source_function: module.function_name109 source_file: src/path/to/file.ts:42110 parameters:111 param_name:112 type: string | number | boolean | object | array113 description: What this parameter controls114 required: true | false115 default: value_if_optional116 returns:117 type: string | object | array118 description: What the tool returns119 side_effects:120 - description of any side effect121 estimated_latency: fast | medium | slow122 suitability_score: 5123```1241254.2. Group logical categories ("Data Queries", "File Ops", "Analysis", "Config").1261274.3. Identify deps between tools ("list_datasets" before "query_dataset").1281294.4. Need wrappers?130 - Simplify complex param objects → flat in131 - Convert raw returns → structured text/JSON132 - Safety guards (read-only wrappers for DB fns)133134**→** Complete YAML spec w/ categories, deps, wrapper notes.135136**If err:** Ambiguous → Step 2 → more src detail. Param types uninferable → flag manual review.137138### Step 5: Generate Tool Spec Doc1391405.1. Final doc sections:141 - **Summary**: Codebase overview, lang, size, date142 - **Recommended Tools**: Full specs from Step 4, grouped143 - **Future Candidates**: Score-2 + refactor recs144 - **Excluded**: Score-1 + rationale145 - **Dependencies**: Tool dep graph146 - **Impl Notes**: Wrappers, auth, transport1471485.2. Save `mcp-tool-spec.yml` (machine) + `mcp-tool-spec.md` (human).1491505.3. Existing MCP server provided → gap analysis:151 - In spec, not impl152 - Impl, not in spec (stale)153 - Spec drift (impl diverges)154155**→** Complete doc → consumable by `scaffold-mcp-server`.156157**If err:** >200 tools → split modules w/ cross-refs. No candidates → "readiness assessment" doc w/ refactor recs.158159## Check160161- [ ] All src files scanned162- [ ] Candidates have names, signatures, returns163- [ ] Each candidate scored + rationale164- [ ] Tool specs complete param schemas w/ types165- [ ] Side effects explicit per tool166- [ ] Doc valid YAML (parseable)167- [ ] Tool names follow MCP (snake_case, unique)168- [ ] Categories + deps coherent169- [ ] Gap analysis if existing MCP provided170- [ ] Future candidates list refactor steps171172## Traps173174- **Too many tools**: AI works best 10-30 focused. Breadth > depth. Resist every public fn.175- **Ignore side effects**: "Just reads" + logs/cache = still side effects. Audit `Grep` file writes, network, DB.176- **Assume type safety**: Dynamic langs (Py, R, JS) may lack type annotations. Infer from usage, flag uncertainty.177- **Missing auth ctx**: Fns working in authed web req may fail via MCP no session. Check implicit session cookies, JWT, env creds.178- **Over-engineer wrappers**: 50-line wrapper → not good candidate. Prefer natural mapping.179- **Neglect err paths**: MCP must return structured errs. Untyped exceptions → err-handling wrappers.180- **Conflate internal + external APIs**: Internal helpers poor candidates. Focus external-consumption or boundary APIs.181- **Skip gap analysis**: Existing MCP provided → always compare. No gap analysis → duplicate work or stale tools.182183## →184185- `scaffold-mcp-server` — use out spec → working MCP186- `build-custom-mcp-server` — manual impl ref187- `configure-mcp-server` — connect to Claude Code/Desktop188- `troubleshoot-mcp-connection` — debug after deploy189- `review-software-architecture` — arch review for tool surface190- `security-audit-codebase` — audit pre-external exposure