Index
code_context_agent.tools ¶
Custom tools package for code context analysis.
This package provides all tools used by the code context agent: - Discovery: File manifests, repomix bundles, ripgrep search - LSP: Language server operations for semantic analysis - ast-grep: Structural code search with rule packs - Shell: Bounded command execution
CommandResult ¶
Bases: TypedDict
Result of a shell command execution.
ToolResult ¶
Bases: FrozenModel
Standardized result structure for tool responses.
Provides a consistent JSON serialization pattern for tool outputs.
Example
result = ToolResult(status="success", data={"count": 42}) return result.to_json() '{"status": "success", "data": {"count": 42}}'
result = ToolResult.error("File not found") return result.to_json() '{"status": "error", "error": "File not found"}'
ValidationError ¶
Bases: ValueError
Raised when input validation fails.
astgrep_inline_rule ¶
Run ast-grep with an inline YAML rule definition.
Use this for custom one-off patterns that aren't in the predefined rule packs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
language | str | Language identifier. | required |
rule_yaml | str | Inline YAML rule definition. | required |
repo_path | str | Repository root path. | required |
include_globs | list[str] | None | Paths to include. | None |
max_results | int | Maximum results. | 100 |
Returns:
| Type | Description |
|---|---|
str | JSON array of matches. |
Example
rule = ''' ... id: find-fetch ... language: TypeScript ... rule: ... pattern: fetch($$ARGS) ... ''' result = astgrep_inline_rule("ts", rule, "/path/to/repo")
Source code in src/code_context_agent/tools/astgrep.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
astgrep_scan ¶
astgrep_scan(
language,
pattern,
repo_path,
include_globs=None,
exclude_globs=None,
max_results=100,
)
Run ast-grep structural search with a pattern.
Performs AST-based structural code search, which is more precise than regex for finding code patterns like function calls, assignments, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
language | str | Language identifier ("ts", "tsx", "py", "js", "jsx"). | required |
pattern | str | ast-grep pattern (e.g., "\(OBJ.\)METHOD($$ARGS)"). | required |
repo_path | str | Repository root path. | required |
include_globs | list[str] | None | Paths to include (e.g., ["src/", "apps/"]). | None |
exclude_globs | list[str] | None | Paths to exclude (e.g., ["/node_modules/"]). | None |
max_results | int | Maximum results to return. | 100 |
Returns:
| Type | Description |
|---|---|
str | JSON array of matches with file, range, and matched text. |
Example
result = astgrep_scan("ts", "\(DB.query(\)\(ARGS)", "/path/to/repo") result = astgrep_scan("py", "\)OBJ.execute($$SQL)", "/path/to/repo", include_globs=["src/**"])
Source code in src/code_context_agent/tools/astgrep.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
astgrep_scan_rule_pack ¶
astgrep_scan_rule_pack(
rule_pack,
repo_path,
include_globs=None,
exclude_globs=None,
max_results=200,
)
Run ast-grep with a predefined rule pack for business logic detection.
Rule packs are YAML files with multiple rules for detecting specific patterns like DB calls, state mutations, and API interactions.
Available rule packs: - "ts_business_logic": TypeScript/JavaScript DB, state, API patterns - "py_business_logic": Python DB, state, HTTP patterns
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_pack | str | Name of the rule pack to use. | required |
repo_path | str | Repository root path. | required |
include_globs | list[str] | None | Paths to include. | None |
exclude_globs | list[str] | None | Paths to exclude. | None |
max_results | int | Maximum results to return. | 200 |
Returns:
| Type | Description |
|---|---|
str | JSON array of matches grouped by rule ID. |
Example
result = astgrep_scan_rule_pack("ts_business_logic", "/path/to/repo")
Source code in src/code_context_agent/tools/astgrep.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
create_file_manifest ¶
Create ignore-aware file manifest using ripgrep.
USE THIS TOOL: As the FIRST step in any codebase analysis workflow. Creates a safe inventory of files without reading contents.
DO NOT USE: - If you already have a manifest from a previous call in this session - If .code-context/files.all.txt exists and is recent
Generates a list of all files in the repository, respecting .gitignore and skipping hidden/binary files. Output is written to .code-context/files.all.txt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
Returns:
| Type | Description |
|---|---|
str | JSON with: |
str |
|
str |
|
Output Size: ~100 bytes JSON + manifest file (~50 bytes per file path)
Common Errors
- "rg not found": ripgrep not installed (install with: cargo install ripgrep)
- Empty manifest: Check if repo_path is correct and contains files
- Permission denied: Ensure read access to the repository
Example success
{"status": "success", "manifest_path": "/repo/.code-context/files.all.txt", "file_count": 847}
Source code in src/code_context_agent/tools/discovery.py
read_file_bounded ¶
Read a file with bounded output for safe analysis.
USE THIS TOOL: - To deeply read and understand business logic files identified by graph analysis, LSP, or AST-grep. Essential for Phase 6.5 (Deep Read). - To read a SINGLE specific file when you know the exact path - To inspect implementation details after finding via rg_search - To read configuration files (package.json, pyproject.toml, etc.) - When you need line numbers for subsequent LSP calls - For files >500 lines, paginate using start_line (e.g., read 1-500, then 501-1000)
DO NOT USE: - To read multiple files at once (use repomix_bundle instead) - For initial exploration before Phase 3 (use repomix_orientation first) - For files >500 lines without specifying start_line for pagination
Reads file contents with line limits to prevent token overflow. Includes line numbers formatted as " 123| code here".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path | str | Absolute path to the file. | required |
max_lines | int | Maximum lines to read (default 500, reduce for large files). | 500 |
start_line | int | Starting line number (1-indexed, use for pagination). | 1 |
Returns:
| Type | Description |
|---|---|
str | JSON with content (with line numbers), path, lines_read, and truncated flag. |
Output Size: ~80 bytes per line average. 500 lines = ~40KB.
Common Errors
- "File not found": Check path is absolute and file exists
- "truncated": true: File has more lines, use start_line to paginate
- UnicodeDecodeError: File is binary, not suitable for text reading
Example success
{"status": "success", "path": "/repo/src/main.py", "content": " 1| ...", "start_line": 1, "lines_read": 150, "truncated": false}
Example pagination (reading lines 500-1000): >>> read_file_bounded("/repo/large_file.py", max_lines=500, start_line=500)
Source code in src/code_context_agent/tools/discovery.py
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 | |
repomix_bundle ¶
repomix_bundle(
file_list_path,
output_path,
compress=True,
include_diffs=False,
include_logs=False,
include_logs_count=50,
split_size=None,
truncate_base64=True,
remove_comments=False,
)
Pack curated files into markdown context bundle.
USE THIS TOOL: When you have a curated list of file paths and want to bundle their contents into a single markdown file for analysis.
DO NOT USE: - For initial exploration (use repomix_orientation first) - If you don't have a file list yet (use write_file_list first)
Takes a list of file paths and bundles their contents into a single markdown file using repomix. The --stdin flag reads paths from the provided file list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_list_path | str | Path to file containing paths to pack (one per line). | required |
output_path | str | Output markdown file path. | required |
compress | bool | Use tree-sitter compression to reduce size. | True |
include_diffs | bool | Include git working tree + staged changes in the bundle. | False |
include_logs | bool | Include recent git commit history in the bundle. | False |
include_logs_count | int | Number of recent commits to include (only when include_logs=True). | 50 |
split_size | str | None | Split output into chunks of this size (e.g., "500kb", "2mb"). Useful for very large bundles that exceed context windows. | None |
truncate_base64 | bool | Truncate base64-encoded data to reduce token waste (default True). | True |
remove_comments | bool | Strip comments from source code for minimal structural output. | False |
Returns:
| Type | Description |
|---|---|
str | JSON with output path, file size, and status. |
Output Size: Varies by file count and content. Compressed bundles are ~30-50% smaller.
Common Errors
- "File list not found": Ensure file_list_path exists and has content
- Timeout after 300s: Too many/large files, reduce scope or use split_size
- "repomix not found": Install with npm install -g repomix
Example
result = repomix_bundle(".code-context/files.targeted.txt", ".code-context/CONTEXT.bundle.md") result = repomix_bundle( ... ".code-context/files.targeted.txt", ... ".code-context/CONTEXT.bundle.md", ... include_diffs=True, ... include_logs=True, ... include_logs_count=20, ... )
Source code in src/code_context_agent/tools/discovery.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
repomix_bundle_with_context ¶
repomix_bundle_with_context(
repo_path,
output_path,
include_patterns=None,
compress=True,
include_diffs=True,
include_logs=True,
include_logs_count=50,
truncate_base64=True,
)
Bundle repository files with git context (diffs and logs).
USE THIS TOOL: When you need a comprehensive snapshot of a repository that includes both file contents and recent git activity. Combines file bundling with git diffs and commit history in a single call.
DO NOT USE: - For initial exploration (use repomix_orientation first) - If you only need file contents without git context (use repomix_bundle) - For very large repos without include_patterns (will be slow/huge)
Unlike repomix_bundle which reads from a file list via --stdin, this tool operates directly on a repo path with optional glob include patterns. It always includes git context (diffs and/or logs) to provide a change-aware view of the codebase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
output_path | str | Output markdown file path. | required |
include_patterns | str | None | Comma-separated glob patterns to include (e.g., "src//*.py,tests//*.py"). If None, includes all files (respecting .gitignore). | None |
compress | bool | Use tree-sitter compression to reduce size. | True |
include_diffs | bool | Include git working tree + staged changes (default True). | True |
include_logs | bool | Include recent git commit history (default True). | True |
include_logs_count | int | Number of recent commits to include (only when include_logs=True). | 50 |
truncate_base64 | bool | Truncate base64-encoded data to reduce token waste (default True). | True |
Returns:
| Type | Description |
|---|---|
str | JSON with output path, file size, and status. |
Output Size
- Small repos with few changes: ~50-200KB
- Medium repos with active changes: ~200KB-1MB
- Execution time: 10-120 seconds depending on repo size and history
Common Errors
- "repomix not found": Install with npm install -g repomix
- Timeout after 300s: Use include_patterns to narrow scope
- Large output: Reduce include_logs_count or use include_patterns
Example
result = repomix_bundle_with_context( ... "/repo", ... ".code-context/CONTEXT.git-aware.md", ... include_patterns="src/**/*.py", ... include_logs_count=20, ... )
Source code in src/code_context_agent/tools/discovery.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
repomix_compressed_signatures ¶
Extract code signatures and types from a repository using Tree-sitter compression.
Produces a minimal structural view: function/method signatures, class declarations, interface/type definitions, imports — with implementation bodies stripped. Also removes comments and empty lines for maximum token efficiency.
Supported languages: JavaScript, TypeScript, Python, Go, Rust, Java, C#, Ruby, PHP, Swift, C, C++, CSS, Solidity, Vue, Dart.
USE THIS TOOL: - For a quick structural overview of specific directories or file patterns - When you need to understand the API surface without reading implementations - To identify function signatures and types across a large codebase efficiently
DO NOT USE: - If you need full implementation details (use repomix_bundle) - For initial codebase overview (use repomix_orientation first) - For non-code files (compression only works on supported languages)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
include_patterns | str | None | Comma-separated glob patterns to include (e.g., "src//*.py,lib//*.ts"). | None |
output_path | str | None | Output path. Defaults to .code-context/CONTEXT.signatures.md | None |
Returns:
| Type | Description |
|---|---|
str | JSON with output path, file size, and status. |
Output Size
- Typically 60-80% smaller than full bundles due to body stripping + comment removal
- Small repos: ~5-30KB
- Medium repos: ~30-150KB
- Execution time: 5-60 seconds
Common Errors
- "repomix not found": Install with npm install -g repomix
- Timeout after 180s: Use include_patterns to narrow scope
- Empty output: No supported language files matched
Example
result = repomix_compressed_signatures("/repo", include_patterns="src/**/*.py") result = repomix_compressed_signatures("/repo") # All files
Source code in src/code_context_agent/tools/discovery.py
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 | |
repomix_json_export ¶
Export repository structure as JSON for programmatic analysis.
USE THIS TOOL: When you need structured data about the repository rather than a human-readable markdown bundle. Useful for getting exact file counts, token distributions, and directory structure as machine-parseable data.
DO NOT USE: - For reading file contents (use repomix_bundle or read_file_bounded) - For initial high-level overview (use repomix_orientation) - If you only need file paths (use create_file_manifest)
Uses repomix --style json to produce structured output that can be parsed programmatically. The output includes file metadata without file contents (--no-files), keeping the output compact.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
include_patterns | str | None | Comma-separated glob patterns to include (e.g., "src//*.py,tests//*.py"). | None |
Returns:
| Type | Description |
|---|---|
str | JSON with output_path and parsed metadata (total_files, total_tokens). |
Output Size: ~200 bytes JSON response + JSON file on disk (~1-50KB depending on repo).
Common Errors
- "repomix not found": Install with npm install -g repomix
- Timeout after 180s: Use include_patterns to narrow scope
- JSON parse error: repomix output format may have changed
Example success
{"status": "success", "output_path": "/repo/.code-context/structure.json", "total_files": 247, "total_tokens": 185420}
Example
result = repomix_json_export("/repo", include_patterns="src//*.py,tests//*.py")
Source code in src/code_context_agent/tools/discovery.py
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | |
repomix_orientation ¶
Generate token-aware orientation snapshot without file contents.
USE THIS TOOL: After create_file_manifest to understand codebase structure and identify high-complexity areas via token distribution.
DO NOT USE: - If repo has >10K files (will auto-skip with recommendation) - If you only need to find specific files (use rg_search instead) - If .code-context/CONTEXT.orientation.md exists and repo hasn't changed
Uses repomix to create a metadata overview including directory structure and token distribution tree. Helps identify where code complexity lies without bundling actual content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
token_threshold | int | Minimum tokens to show in tree (filters noise). | 300 |
max_file_count | int | Maximum files allowed before skipping (default 10000). | 10000 |
Returns:
| Type | Description |
|---|---|
str | JSON with output path and status, or skipped status for large repos. |
Output Size
- Small repos (<500 files): ~5-20KB markdown
- Medium repos (500-2000 files): ~20-100KB markdown
- Large repos (2000-10000 files): ~100-500KB markdown
- Execution time: 5-60 seconds depending on repo size
Common Errors
- "repomix not found": Install with npm install -g repomix
- "skipped" status: Repo exceeds max_file_count, use --include patterns
- Timeout after 180s: Repo too large, reduce scope with glob patterns
Example success
{"status": "success", "output_path": "/repo/.code-context/CONTEXT.orientation.md"}
Example skipped
{"status": "skipped", "reason": "Repository has 15000 files (max: 10000)"}
Source code in src/code_context_agent/tools/discovery.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
repomix_split_bundle ¶
Pack files into multiple split bundles for large codebases.
When a codebase is too large for a single context window, this tool splits the output into numbered files (e.g., output.1.md, output.2.md).
USE THIS TOOL: - When a previous repomix_bundle call produced output exceeding context limits - For large codebases where you want to process files in manageable chunks - When you need to parallelize analysis across multiple context windows
DO NOT USE: - For small repos that fit in a single bundle (use repomix_bundle) - For initial exploration (use repomix_orientation first) - If you don't have a file list yet (use write_file_list first)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_list_path | str | Path to file containing paths to pack (one per line). | required |
output_dir | str | Directory for split output files. | required |
max_size | str | Maximum size per file (e.g., "500kb", "1mb", "2mb"). | '500kb' |
compress | bool | Use tree-sitter compression. | True |
Returns:
| Type | Description |
|---|---|
str | JSON with output directory, file count, and individual file paths. |
Output Size: Each split file will be at most max_size. Total output depends on input.
Common Errors
- "File list not found": Ensure file_list_path exists and has content
- Timeout after 300s: Reduce the number of files in the list
- "repomix not found": Install with npm install -g repomix
Example
result = repomix_split_bundle(".code-context/files.all.txt", ".code-context/splits/", max_size="1mb")
Source code in src/code_context_agent/tools/discovery.py
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 | |
rg_search ¶
rg_search(
pattern,
repo_path,
glob=None,
file_type=None,
max_count=100,
context_lines=0,
count_only=False,
)
Search for pattern in repository using ripgrep.
USE THIS TOOL: - To find entrypoints (e.g., "def main", "createServer", "app.listen") - To locate specific functions, classes, or patterns - To discover imports and dependencies - When you know WHAT to search for but not WHERE - With count_only=True for precise occurrence counts across the entire codebase
DO NOT USE: - For listing all files (use create_file_manifest instead) - For reading file contents (use read_file_bounded instead) - For structural analysis (use lsp_document_symbols instead)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern | str | Regex pattern to search for. | required |
repo_path | str | Repository root path. | required |
glob | str | None | Optional glob filter (e.g., ".py", "src/**/.ts"). | None |
file_type | str | None | Optional file type (e.g., "py", "ts", "js"). | None |
max_count | int | Maximum matches to return per file (default 100). | 100 |
context_lines | int | Lines of context around matches (0-5 recommended). | 0 |
count_only | bool | Return only match counts per file (no match details). Uses rg --count for exact totals without truncation. | False |
Returns:
| Type | Description |
|---|---|
str | JSON with matches array containing path, line_number, and lines. |
str | When count_only=True: JSON with total_count and per-file counts. |
~200 bytes per match. Results capped at 500 lines.
count_only mode: ~50 bytes per file, no cap.
Pattern Tips
- Literal strings: "createServer" (no regex escaping needed)
- Function definitions: "def \w+(" or "function \w+("
- Class definitions: "class \w+"
- Imports: "import|from .* import"
- Case insensitive: Use "(?i)pattern"
Common Errors
- "rg not found": ripgrep not installed
- Empty matches with valid pattern: Try broader glob or check file_type
- Regex syntax error: Escape special chars like ( ) [ ] { }
Example success
{"status": "success", "pattern": "def main", "matches": [...], "match_count": 3}
Example count_only
{"status": "success", "pattern": "TODO", "total_count": 42, "files": {"src/main.py": 12, "src/utils.py": 30}, "file_count": 2}
Example searches
rg_search("def main", "/repo", glob="*.py") # Python entrypoints rg_search("createServer", "/repo", file_type="ts") # TS server setup rg_search("TODO|FIXME", "/repo", count_only=True) # Exact count across repo
Source code in src/code_context_agent/tools/discovery.py
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 | |
write_file ¶
Write content to a file in the output directory.
USE THIS TOOL: - To write CONTEXT.md and other analysis output files - To save narrated context, summaries, or generated documentation - For any file that needs to be created or overwritten in .code-context/
DO NOT USE: - For writing file lists (use write_file_list instead) - For writing to paths outside the analysis output directory
Security: Only allows writing to paths within the .code-context/ output directory to prevent unintended modifications to the analyzed repository.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path | str | Absolute path to the file to write. Must be within a .code-context/ directory. | required |
content | str | String content to write to the file. | required |
Returns:
| Type | Description |
|---|---|
str | JSON with status, path, and bytes written. |
Example
write_file("/repo/.code-context/CONTEXT.md", "# Project Context\n\n## Summary\n...")
Source code in src/code_context_agent/tools/discovery.py
write_file_list ¶
Write a list of file paths to a file for repomix bundling.
Use this to create the curated file list before calling repomix_bundle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_paths | list[str] | List of file paths to include in the bundle. | required |
output_path | str | Path to write the file list. | required |
Returns:
| Type | Description |
|---|---|
str | JSON with output path and file count. |
Example
result = write_file_list(["src/main.ts", "src/utils.ts"], ".code-context/files.targeted.txt")
Source code in src/code_context_agent/tools/discovery.py
git_blame_summary ¶
Get authorship summary for a file.
USE THIS TOOL: - To identify who has expertise on a file - To understand code ownership distribution - To find the right person to ask about code - To see how recently different parts were modified
DO NOT USE: - For files not tracked by git - When you need line-by-line attribution (use git blame directly)
Provides a summary of who wrote which portions of a file, aggregated by author.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
file_path | str | Path to the file (relative to repo root or absolute). | required |
Returns:
| Type | Description |
|---|---|
str | JSON with author breakdown by lines owned. |
Output Size: ~100 bytes per author.
Example success
{"status": "success", "file_path": "src/main.py", "total_lines": 150, "authors": [{"email": "dev@example.com", "lines": 100, "percentage": 66.7, "last_commit_date": "2024-01-15"}]}
Source code in src/code_context_agent/tools/git.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
git_contributors ¶
Get contributor statistics for the repository.
USE THIS TOOL: - To identify key contributors and their areas of focus - To understand team structure and expertise distribution - To find domain experts for specific areas
DO NOT USE: - When you only need file-specific authorship (use git_blame_summary instead)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
limit | int | Maximum commits to analyze (default 100). | 100 |
Returns:
| Type | Description |
|---|---|
str | JSON with contributors ranked by commit count. |
Output Size: ~100 bytes per contributor.
Example success
{"status": "success", "contributors": [ {"email": "dev1@example.com", "commits": 50, "percentage": 50.0, "first_commit": "2023-06-01", "last_commit": "2024-01-15"} ], "total_commits": 100}
Source code in src/code_context_agent/tools/git.py
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 | |
git_diff_file ¶
Get the diff for a specific file.
USE THIS TOOL: - To see exact changes in a file - To understand what changed between commits - For code review or change analysis - To investigate recent modifications
DO NOT USE: - For large binary files - When you need full file content (use read_file_bounded instead)
Shows the unified diff for a file. Without a commit, shows unstaged changes. With a commit hash, shows changes introduced by that commit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
file_path | str | Path to the file (relative to repo root or absolute). | required |
commit | str | None | Optional commit hash to show changes from that commit. | None |
context_lines | int | Lines of context around changes (default 3). | 3 |
Returns:
| Type | Description |
|---|---|
str | JSON with diff content and metadata. |
Output Size: Varies by change size, typically 1-10KB.
Example success
{"status": "success", "file_path": "src/main.py", "commit": "abc123", "diff": "@@ -10,5 +10,7 @@..."}
Source code in src/code_context_agent/tools/git.py
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
git_file_history ¶
Get commit history for a specific file.
USE THIS TOOL: - To understand how a file has evolved over time - To find when specific changes were introduced - To identify who has worked on a file - To trace the intent behind changes via commit messages
DO NOT USE: - For repository-wide history (use git_recent_commits instead) - For files not yet tracked by git
Returns recent commits that touched the specified file, including commit messages which often explain the "why" behind changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
file_path | str | Path to the file (relative to repo root or absolute). | required |
limit | int | Maximum commits to return (default 20). | 20 |
Returns:
| Type | Description |
|---|---|
str | JSON with commits array containing hash, author, date, and message. |
Output Size: ~200 bytes per commit.
Example success
{"status": "success", "file_path": "src/main.py", "commits": [{"hash": "abc123", "author": "dev@example.com", "date": "2024-01-15", "message": "Fix auth bug"}]}
Source code in src/code_context_agent/tools/git.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
git_files_changed_together ¶
Find files that frequently change together with a given file (coupling detection).
USE THIS TOOL: - To identify tightly coupled files that may need to change together - To understand implicit dependencies not captured by imports - To find related files when making changes - To detect architectural coupling patterns
DO NOT USE: - For untracked files (not yet in git) - For files with no commit history
Analyzes git history to find files that appear in the same commits as the target file, ranked by co-occurrence frequency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
file_path | str | Path to the file (relative to repo root or absolute). | required |
limit | int | Maximum number of commits to analyze (default 100). | 100 |
Returns:
| Type | Description |
|---|---|
str | JSON with: |
str |
|
str |
|
str |
|
Output Size: ~100 bytes per co-changed file.
Example success
{"status": "success", "file_path": "src/auth.py", "total_commits": 45, "cochanged_files": [{"path": "src/user.py", "count": 20, "percentage": 44.4}, ...]}
Example patterns detected
- High coupling (>50%): Files should possibly be merged or abstracted
- Medium coupling (20-50%): Normal feature-level coupling
- Low coupling (<20%): Incidental changes, less significant
Source code in src/code_context_agent/tools/git.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
git_hotspots ¶
Identify frequently changed files (change hotspots).
USE THIS TOOL: - To find areas of high activity/churn - To identify potentially problematic code (frequent changes may indicate bugs) - To prioritize code review or refactoring efforts - To understand where development effort is concentrated
DO NOT USE: - For small repositories with little history
Analyzes git history to find files with the most commits, which often indicates areas of active development or instability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
limit | int | Maximum commits to analyze (default 50). | 50 |
since | str | None | Optional date filter (e.g., "2024-01-01", "6 months ago"). | None |
Returns:
| Type | Description |
|---|---|
str | JSON with hotspots ranked by commit frequency. |
Output Size: ~80 bytes per file.
Example success
{"status": "success", "hotspots": [ {"path": "src/auth.py", "commits": 25, "percentage": 50.0}, {"path": "src/api.py", "commits": 15, "percentage": 30.0} ], "total_commits_analyzed": 50}
Interpretation
- High commit files may need: better tests, refactoring, or documentation
- Stable files (few commits) are often mature/well-designed
Source code in src/code_context_agent/tools/git.py
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 | |
git_recent_commits ¶
Get recent commits from the repository.
USE THIS TOOL: - To understand recent development activity - To identify active areas of the codebase - To see the general direction of development - To find commits relevant to a feature or bug
DO NOT USE: - For file-specific history (use git_file_history instead)
Returns recent commits from the specified branch with messages that provide context about development activity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path | str | Absolute path to the repository root. | required |
limit | int | Maximum commits to return (default 30). | 30 |
branch | str | Branch or ref to query (default HEAD). | 'HEAD' |
Returns:
| Type | Description |
|---|---|
str | JSON with commits array containing hash, author, date, message, |
str | and files_changed count. |
Output Size: ~250 bytes per commit.
Example success
{"status": "success", "branch": "main", "commits": [{"hash": "abc123", "author": "dev@example.com", "date": "2024-01-15", "message": "Add feature X", "files_changed": 5}]}
Source code in src/code_context_agent/tools/git.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
code_graph_analyze ¶
code_graph_analyze(
graph_id,
analysis_type,
top_k=10,
node_a="",
node_b="",
resolution=1.0,
category="",
)
Run graph algorithms to surface structural insights about the codebase.
USE THIS TOOL: - After populating graph with code_graph_ingest_* tools - To find important code that isn't obvious from file names - To understand code relationships and architecture
DO NOT USE: - On an empty graph (ingest data first) - For simple lookups (use code_graph_explore instead)
Analysis types provide different perspectives:
Centrality (finds important code): - "hotspots": Betweenness centrality. Finds bottleneck code that many paths go through. High score = integration point, likely to cause cascading changes. Use for: risk assessment, refactoring targets. - "foundations": PageRank. Finds core infrastructure that other important code depends on. High score = foundational code. Use for: understanding dependencies, documentation priority. - "entry_points": Nodes with no incoming edges but outgoing calls. These start execution flows. Use for: understanding app structure.
Clustering (finds groupings): - "modules": Louvain community detection. Finds densely connected groups = logical modules/layers. Use for: architecture diagrams, understanding boundaries.
Relationships (between specific nodes): - "coupling": Measures how tightly two nodes are connected. Use for: understanding change impact, identifying tight coupling. - "similar": Personalized PageRank from a node. Finds related code. Use for: understanding a node's neighborhood. - "dependencies": BFS from a node. Shows what it depends on. Use for: understanding impact of changes.
Filtering: - "category": Finds all nodes in a business logic category. Use for: focused analysis on db/auth/validation/etc.
Code Health: - "unused_symbols": Finds functions/classes/methods with zero cross-file references. Dead code candidates. Use category param for node type filter. - "refactoring": Combines clone detection, code smells, and unused symbols into ranked refactoring opportunities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the graph to analyze (must have data from ingestion) | required |
analysis_type | str | Algorithm to run. One of: - "hotspots": Returns ranked list by betweenness score - "foundations": Returns ranked list by PageRank score - "entry_points": Returns list of entry point nodes - "modules": Returns list of detected modules with members - "coupling": Returns coupling metrics (requires node_a, node_b) - "similar": Returns similar nodes (requires node_a) - "category": Returns nodes in category (requires category) - "dependencies": Returns dependency chain (requires node_a) - "trust": TrustRank-based foundations (noise-resistant PageRank from entry points) - "triangles": Find tightly-coupled code triads - "unused_symbols": Dead code detection (zero cross-file references) - "refactoring": Combined refactoring opportunity ranking | required |
top_k | int | Maximum results for ranked analyses (hotspots, foundations, similar). Default 10. Use 20-30 for comprehensive analysis. | 10 |
node_a | str | Required for "coupling", "similar", "dependencies". Node ID format: "file_path:symbol_name" | '' |
node_b | str | Required for "coupling" analysis. Second node to compare. | '' |
resolution | float | For "modules" only. Controls cluster granularity: - < 1.0: Fewer, larger clusters (e.g., 0.5 for high-level layers) - = 1.0: Default clustering - > 1.0: More, smaller clusters (e.g., 1.5 for fine-grained) | 1.0 |
category | str | Required for "category" analysis. Category name from AST-grep rule packs: "db", "auth", "http", "validation", etc. | '' |
Returns:
| Name | Type | Description |
|---|---|---|
str | JSON with analysis results. Format varies by type: | |
str | hotspots/foundations: | |
str | {"results": [{"id": "...", "score": 0.85, "name": "...", ...}]} | |
modules | str | |
str | {"module_count": 5, "results": [ | |
str | ]} | |
coupling | str | |
str | {"results": {"coupling": 2.5, "shared_neighbors": 3, "path_length": 2}} |
Output Size: 1-10KB depending on top_k and analysis type
Workflow Examples:
Find bottleneck code
hotspots = code_graph_analyze("main", "hotspots", top_k=15)
Results ranked by betweenness - top items are integration points¶
Detect architecture layers
modules = code_graph_analyze("main", "modules", resolution=0.8)
Each module is a logical grouping - name based on key_nodes¶
Understand coupling
coupling = code_graph_analyze("main", "coupling", node_a="src/api.py:handler", node_b="src/db.py:repository")
High coupling score = tightly connected, changes propagate¶
Find all database operations
db_ops = code_graph_analyze("main", "category", category="db")
Returns all nodes tagged as "db" from AST-grep ingestion¶
Source code in src/code_context_agent/tools/graph/tools.py
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 | |
code_graph_create ¶
Initialize an empty code graph for structural analysis of a codebase.
USE THIS TOOL: - At the start of analysis, BEFORE running LSP/AST-grep tools - When you need to unify results from multiple discovery tools - When you want to run graph algorithms (hotspots, modules, coupling)
DO NOT USE: - If a graph with this ID already exists (will overwrite it) - For simple single-file analysis (use LSP tools directly)
The graph is stored in memory for the session. Populate it using: - code_graph_ingest_lsp: Add symbols, references, definitions from LSP - code_graph_ingest_astgrep: Add business logic patterns - code_graph_ingest_tests: Add test coverage relationships
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | Unique identifier for this graph. Use descriptive names: - "main": Primary analysis graph for the whole codebase - "feature_auth": Graph focused on authentication code - "module_api": Graph for API layer only | required |
description | str | Human-readable description of what this graph represents. Helps when managing multiple graphs. | '' |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | {"status": "success", "graph_id": "...", "message": "..."} |
Output Size: ~100 bytes
Workflow
- code_graph_create("main") # Initialize
- lsp_start(...) + lsp_document_symbols(...) # Discover
- code_graph_ingest_lsp(...) # Populate
- code_graph_analyze("main", "hotspots") # Analyze
- code_graph_save("main", ".code-context/graph.json") # Persist
Example
code_graph_create("main", "Full codebase analysis") code_graph_create("backend", "Backend services only")
Source code in src/code_context_agent/tools/graph/tools.py
code_graph_explore ¶
code_graph_explore(
graph_id,
action,
node_id="",
module_id=-1,
target_node="",
depth=1,
category="",
)
Progressively explore the code graph to build context incrementally.
USE THIS TOOL: - ALWAYS start with "overview" action first - When you need to understand the codebase step by step - To get suggestions on where to explore next - To track what you've already explored
DO NOT USE: - For running analysis algorithms (use code_graph_analyze instead) - On an empty graph (ingest data first)
Progressive disclosure pattern: 1. "overview" → Get entry points, hotspots, modules, foundations 2. Pick interesting nodes from overview 3. "expand_node" → See neighbors and relationships 4. Repeat until sufficient context is gathered
The explorer tracks visited nodes and suggests what to explore next.
Actions:
Starting point: - "overview": Returns high-level structure. Includes: - entry_points: Where execution starts - hotspots: Bottleneck code (top 5) - modules: Detected clusters with key nodes - foundations: Core infrastructure (top 5) Always start here to orient yourself.
Drill-down: - "expand_node": BFS expansion from a node. See immediate neighbors and their relationships. Good for understanding a specific area. - "expand_module": Deep-dive into a detected module. Shows internal structure and external connections. - "category": Explore all nodes in a business logic category. Groups results by file.
Navigation: - "path": Find shortest path between two nodes. Useful for understanding how components connect. - "status": Check exploration coverage (% of nodes visited). - "reset": Clear exploration state to start fresh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the graph to explore (must have data from ingestion) | required |
action | str | Exploration action. One of: - "overview": No additional params needed - "expand_node": Requires node_id, optional depth - "expand_module": Requires module_id (from overview/modules analysis) - "path": Requires node_id (source) and target_node - "category": Requires category (e.g., "db", "auth") - "status": No additional params - "reset": No additional params | required |
node_id | str | For "expand_node": Node ID to expand from. For "path": Source node. Format: "file_path:symbol_name" | '' |
module_id | int | For "expand_module": Module ID from detect_modules results. Typically 0, 1, 2, etc. from the overview. | -1 |
target_node | str | For "path": Destination node ID. | '' |
depth | int | For "expand_node": How many hops to expand. - depth=1: Direct neighbors only (fast, focused) - depth=2: Neighbors of neighbors (broader context) - depth=3+: Rarely needed, can be large | 1 |
category | str | For "category": Business logic category name. Values from AST-grep: "db", "auth", "http", "validation", etc. | '' |
Returns:
| Name | Type | Description |
|---|---|---|
str | JSON with exploration results. Always includes "explored_count". | |
overview | str | |
str | { "entry_points": [...], "hotspots": [...], "modules": [{"module_id": 0, "size": 15, "key_nodes": [...]}], "foundations": [...], "explored_count": 25 | |
str | } | |
expand_node | str | |
str | { "center": "src/api.py:handler", "discovered_nodes": [...], "edges": [...], "suggested_next": [...], # What to explore next "explored_count": 40 | |
str | } |
Output Size: 2-20KB depending on action and graph size
Workflow Example:
1. Start with overview¶
overview = code_graph_explore("main", "overview")
Look at entry_points and hotspots¶
2. Expand from interesting hotspot¶
details = code_graph_explore("main", "expand_node", node_id=overview["hotspots"][0]["id"], depth=2)
See neighbors and suggested_next¶
3. Explore a module¶
module_details = code_graph_explore("main", "expand_module", module_id=0)
See internal structure and external connections¶
4. Check coverage¶
status = code_graph_explore("main", "status")
coverage_percent shows how much of graph was explored¶
Source code in src/code_context_agent/tools/graph/tools.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 | |
code_graph_export ¶
Export the code graph for visualization or external analysis.
USE THIS TOOL: - To generate Mermaid diagrams for CONTEXT.md architecture section - To save graph data for external visualization tools - After analysis, to capture the graph structure
DO NOT USE: - For persistence (use code_graph_save instead) - On empty graphs (ingest data first)
Export formats:
"mermaid" (recommended for documentation): Generates Mermaid diagram syntax that can be embedded in markdown. - Selects top nodes by degree (most connected = most important) - Uses shapes based on node type: - [name]: Classes (rectangles) - (name): Functions/methods (rounded) - [[name]]: Files (stadium shape) - Edge styles by relationship: - → : calls - -.-> : imports - ==> : inherits
"json" (for external tools): NetworkX node-link format. Can be loaded into other graph tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the graph to export (must exist) | required |
format | str | Export format: - "mermaid": Mermaid diagram syntax (for markdown embedding) - "json": NetworkX node-link JSON (for external tools) | 'json' |
include_metadata | bool | For "json" format only. Whether to include node/edge metadata (file_path, line numbers, etc.). Set False for smaller output. | True |
max_nodes | int | For "mermaid" format only. Maximum nodes to include. Mermaid diagrams become unreadable with too many nodes. Recommended: 15 for CONTEXT.md, up to 50 for detailed diagrams. Nodes are selected by degree (most connected first). | 100 |
Returns:
| Type | Description |
|---|---|
str | For "mermaid": |
str | { "status": "success", "format": "mermaid", "diagram": "graph TD\n node1[Name] → node2..." |
str | } |
str | For "json": |
str | { "status": "success", "format": "json", "graph": {"nodes": [...], "links": [...]} |
str | } |
Output Size
- mermaid: 1-5KB (limited by max_nodes)
- json: 10-500KB (depends on graph size)
Workflow Example:
Export for CONTEXT.md architecture diagram¶
result = code_graph_export("main", format="mermaid", max_nodes=15) mermaid_code = result["diagram"]
Embed in markdown:¶
```mermaid¶
{mermaid_code}¶
```¶
Export for external visualization¶
result = code_graph_export("main", format="json", include_metadata=True)
Use with Gephi, D3.js, etc.¶
Source code in src/code_context_agent/tools/graph/tools.py
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 | |
code_graph_ingest_astgrep ¶
Add AST-grep pattern matches to the graph as categorized business logic nodes.
USE THIS TOOL: - After running astgrep_scan_rule_pack to add business logic patterns - After running astgrep_scan for custom pattern matches - When you want graph analysis to consider business logic categories
DO NOT USE: - Before code_graph_create (graph must exist first) - With empty AST-grep results (check match count first)
AST-grep matches become nodes with rich metadata: - category: "db", "auth", "http", "validation", etc. - severity: "error" (writes), "warning" (reads), "hint" (definitions) - rule_id: The specific pattern that matched
This metadata enables category-based analysis: - code_graph_analyze("main", "category", category="db") - code_graph_explore("main", "category", category="auth")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the target graph (must exist from code_graph_create) | required |
astgrep_result | str | The raw JSON string output from astgrep_scan or astgrep_scan_rule_pack. Pass the exact return value. | required |
result_type | str | Source of the AST-grep result: - "rule_pack" (default): From astgrep_scan_rule_pack. Results include category, severity, rule_id metadata. Use this for business logic detection. - "scan": From astgrep_scan ad-hoc patterns. Results have pattern info but no category metadata. | 'rule_pack' |
Returns:
| Type | Description |
|---|---|
str | JSON with ingestion results: |
str | { "status": "success", "nodes_added": 25, "categories": ["db", "auth", "validation"], "total_nodes": 175 |
str | } |
Output Size: ~300 bytes
Common Errors
- "Graph not found": Call code_graph_create first
- "Invalid JSON": AST-grep result is malformed
Workflow Example
Run rule pack for Python business logic¶
matches = astgrep_scan_rule_pack("py_business_logic", repo_path)
Ingest into graph¶
code_graph_ingest_astgrep("main", matches, "rule_pack")
Now analyze by category¶
db_ops = code_graph_analyze("main", "category", category="db") auth_ops = code_graph_analyze("main", "category", category="auth")
Source code in src/code_context_agent/tools/graph/tools.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
code_graph_ingest_inheritance ¶
Add class inheritance/implementation edges from LSP hover information.
USE THIS TOOL: - After lsp_hover on a class to capture extends/implements relationships - When building class hierarchy for OOP codebases - In DEEP mode for comprehensive type analysis
DO NOT USE: - On non-class symbols (functions, variables) - Without first creating the class node via code_graph_ingest_lsp
Parses class signatures to create edges: - "inherits" edges: class Foo extends Bar → Foo --inherits→ Bar - "implements" edges: class Foo implements IBar → Foo --implements→ IBar
Works with common patterns: - TypeScript/JavaScript: extends, implements - Python: class Foo(Bar, Baz) - Java: extends, implements
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the target graph (must exist from code_graph_create) | required |
hover_content | str | The markdown/text content from lsp_hover result. Extract the "value" field from the hover response. Example: "class UserService extends BaseService implements IUserService" | required |
class_node_id | str | The node ID of the class in the graph. Format: "file_path:ClassName" (e.g., "src/services/user.ts:UserService") Must match the ID created by code_graph_ingest_lsp. | required |
file_path | str | Path to the file containing this class. Used to resolve base class locations. | required |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | {"status": "success", "edges_added": N, "edge_types": ["inherits", "implements"]} |
Output Size: ~200 bytes
Workflow Example
Get class symbols¶
symbols = lsp_document_symbols(session_id, "src/user.ts") code_graph_ingest_lsp("main", symbols, "symbols", source_file="src/user.ts")
For each class, get hover info and ingest inheritance¶
hover = lsp_hover(session_id, "src/user.ts", class_line, 0) hover_content = hover["hover"]["contents"]["value"] code_graph_ingest_inheritance("main", hover_content, "src/user.ts:UserService", "src/user.ts")
Source code in src/code_context_agent/tools/graph/tools.py
code_graph_ingest_lsp ¶
Add LSP tool results to the code graph as nodes and edges.
USE THIS TOOL: - After calling lsp_document_symbols to add function/class nodes - After calling lsp_references to add "references" edges (fan-in data) - After calling lsp_definition to add "calls" edges (call relationships)
DO NOT USE: - Before calling code_graph_create (graph must exist first) - With invalid/empty LSP results (check LSP tool status first)
Converts raw LSP data into graph structure: - "symbols" → Creates nodes for functions, classes, methods, variables - "references" → Creates edges showing where a symbol is used - "definition" → Creates edges showing what a symbol calls/uses
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the target graph (must exist from code_graph_create) | required |
lsp_result | str | The raw JSON string output from an LSP tool. Pass the exact return value from lsp_document_symbols, lsp_references, or lsp_definition. | required |
result_type | str | Type of LSP result being ingested: - "symbols": From lsp_document_symbols. Creates nodes. REQUIRES source_file parameter. - "references": From lsp_references. Creates reference edges. REQUIRES source_symbol parameter (format: "file:name"). - "definition": From lsp_definition. Creates call/import edges. | required |
source_file | str | Required for "symbols" type. The file path that was analyzed (e.g., "src/main.py"). Used to create node IDs. | '' |
source_symbol | str | Required for "references" type. The symbol ID that references point TO (format: "src/main.py:my_function"). | '' |
Returns:
| Type | Description |
|---|---|
str | JSON with ingestion results: |
str | { "status": "success", "nodes_added": 15, # New nodes created "edges_added": 8, # New edges created "total_nodes": 150, # Graph totals "total_edges": 200 |
str | } |
Output Size: ~200 bytes
Common Errors
- "Graph not found": Call code_graph_create first
- "source_file required": Must provide source_file for "symbols"
- "source_symbol required": Must provide source_symbol for "references"
- "Invalid JSON": LSP result is malformed
Workflow Examples:
Ingesting symbols (creates nodes): symbols = lsp_document_symbols(session_id, "src/api.py") code_graph_ingest_lsp("main", symbols, "symbols", source_file="src/api.py")
Ingesting references (creates edges showing fan-in): refs = lsp_references(session_id, "src/api.py", 10, 5) code_graph_ingest_lsp("main", refs, "references", source_symbol="src/api.py:handle_request")
Ingesting definitions (creates call edges): defn = lsp_definition(session_id, "src/api.py", 15, 20) code_graph_ingest_lsp("main", defn, "definition")
Source code in src/code_context_agent/tools/graph/tools.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
code_graph_ingest_rg ¶
Add ripgrep search matches to the graph as preliminary nodes.
USE THIS TOOL: - When LSP doesn't cover a language/pattern - For text-based patterns (SQL keywords, config values, comments) - As a fallback when semantic analysis isn't available
DO NOT USE: - When LSP symbols are available (prefer code_graph_ingest_lsp) - For structural patterns (prefer code_graph_ingest_astgrep)
Creates lightweight nodes from text matches. These nodes have: - file_path and line number - matched text content - No semantic type information (unlike LSP nodes)
Ripgrep nodes are useful for: - Finding TODO/FIXME comments - Locating hardcoded values - Identifying SQL queries in strings
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the target graph (must exist from code_graph_create) | required |
rg_result | str | The raw JSON string output from rg_search tool. Pass the exact return value. | required |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | {"status": "success", "nodes_added": N, "total_nodes": M} |
Output Size: ~150 bytes
Workflow Example
Find all SQL queries¶
sql_matches = rg_search("SELECT|INSERT|UPDATE|DELETE", repo_path) code_graph_ingest_rg("main", sql_matches)
Source code in src/code_context_agent/tools/graph/tools.py
code_graph_ingest_tests ¶
Add test-to-production file mappings as "tests" edges in the graph.
USE THIS TOOL: - After identifying test files (via rg_search for test patterns) - To enable test coverage analysis on business logic - To find untested hotspots in the codebase
DO NOT USE: - With unfiltered file lists (only include actual test files) - Before adding production file nodes to the graph
Creates "tests" edges based on naming convention matching: - test_foo.py → foo.py - foo.test.ts → foo.ts - FooTest.java → Foo.java - tests/foo.test.js → src/foo.js
These edges enable: - Finding untested business logic (nodes without incoming test edges) - Understanding test coverage per module - Prioritizing testing efforts on hotspots
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the target graph (must exist from code_graph_create) | required |
test_files | str | JSON array of test file paths as a string. Example: '["tests/test_user.py", "tests/test_auth.py"]' Obtain from rg_search or file manifest filtering. | required |
production_files | str | JSON array of production file paths as a string. Example: '["src/user.py", "src/auth.py"]' Should include all files you want to map tests to. | required |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | {"status": "success", "edges_added": N, "total_edges": M} |
Output Size: ~150 bytes
Workflow Example
Find test files¶
test_matches = rg_search("def test_|it(|describe(", repo_path) test_files = extract_unique_files(test_matches)
Get production files from manifest¶
prod_files = filter_non_test_files(manifest)
Create test mapping edges¶
code_graph_ingest_tests("main", json.dumps(test_files), json.dumps(prod_files))
Find untested hotspots¶
hotspots = code_graph_analyze("main", "hotspots", top_k=10)
Check which have no incoming "tests" edges¶
Source code in src/code_context_agent/tools/graph/tools.py
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | |
code_graph_load ¶
Load a previously saved code graph from disk.
USE THIS TOOL: - At the start of a session if .code-context/code_graph.json exists - To resume analysis from a previous session - To skip re-running LSP/AST-grep data collection
DO NOT USE: - If graph file doesn't exist (check with file system first) - When you need fresh analysis (create new graph instead)
Loading a saved graph restores: - All nodes with their metadata - All edges with their types - Ready for immediate analysis (code_graph_analyze, code_graph_explore)
Note: Loading replaces any existing graph with the same ID. The explorer state is reset (tracked exploration cleared).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID to assign to the loaded graph. Use: - "main": For the primary codebase graph - Descriptive names for scoped graphs | required |
file_path | str | Path to the saved graph file. Standard location: ".code-context/code_graph.json" | required |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | { "status": "success", "graph_id": "main", "path": ".code-context/code_graph.json", "nodes": 150, "edges": 200 |
str | } |
Output Size: ~100 bytes
Common Errors
- "Load failed": File not found or invalid JSON
Workflow Example:
Check if saved graph exists¶
If .code-context/code_graph.json exists:¶
code_graph_load("main", ".code-context/code_graph.json")
Graph is ready for analysis¶
hotspots = code_graph_analyze("main", "hotspots") overview = code_graph_explore("main", "overview")
No need to re-run lsp_* or astgrep_* tools!¶
Source code in src/code_context_agent/tools/graph/tools.py
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 | |
code_graph_save ¶
Persist the code graph to disk for reuse in future sessions.
USE THIS TOOL: - After completing graph analysis (DEEP mode) - When you want to preserve analysis results - Before ending a session with valuable graph data
DO NOT USE: - For exporting to visualization formats (use code_graph_export) - On empty graphs (waste of disk space)
Saves the complete graph structure including: - All nodes with metadata (file_path, line numbers, categories) - All edges with types (calls, references, imports, inherits) - All analysis-relevant data
Saved graphs can be reloaded with code_graph_load, avoiding the need to re-run LSP/AST-grep tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the graph to save (must exist) | required |
file_path | str | Destination file path. Recommended locations: - ".code-context/code_graph.json": Standard location for main graph - ".code-context/{name}_graph.json": For named/scoped graphs Parent directories are created automatically. | required |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | { "status": "success", "graph_id": "main", "path": ".code-context/code_graph.json", "nodes": 150, "edges": 200 |
str | } |
Output Size: ~100 bytes (file size varies: 10KB-1MB)
Common Errors
- "Graph not found": Graph ID doesn't exist
- "Save failed": File system error (permissions, disk full)
Workflow Example:
After comprehensive analysis in DEEP mode¶
code_graph_create("main")
... ingest LSP, AST-grep data ...¶
... run analysis ...¶
Save for future sessions¶
code_graph_save("main", ".code-context/code_graph.json")
In future session:¶
code_graph_load("main", ".code-context/code_graph.json")
Graph restored with all nodes/edges¶
Source code in src/code_context_agent/tools/graph/tools.py
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 | |
code_graph_stats ¶
Get summary statistics about a code graph.
USE THIS TOOL: - To verify graph was populated correctly after ingestion - To understand graph composition before analysis - For the completion signal (graph node/edge counts)
DO NOT USE: - For detailed analysis (use code_graph_analyze) - For exploration (use code_graph_explore)
Returns counts broken down by type: - Nodes by type: function, class, method, variable, pattern_match - Edges by type: calls, references, imports, inherits, tests
This helps verify: - LSP ingestion worked (function/class nodes exist) - AST-grep ingestion worked (pattern_match nodes exist) - Reference tracking worked (references edges exist) - Test mapping worked (tests edges exist)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id | str | ID of the graph to get stats for (must exist) | required |
Returns:
| Name | Type | Description |
|---|---|---|
JSON | str | { "status": "success", "graph_id": "main", "total_nodes": 150, "total_edges": 200, "nodes_by_type": { "function": 80, "class": 20, "method": 40, "pattern_match": 10 }, "edges_by_type": { "calls": 100, "references": 60, "imports": 30, "tests": 10 } |
str | } |
Output Size: ~300 bytes
Workflow Example:
After ingestion, verify graph state¶
stats = code_graph_stats("main")
Check ingestion worked¶
if stats["nodes_by_type"]["function"] == 0: # LSP symbols not ingested properly
if stats["edges_by_type"]["references"] == 0: # LSP references not ingested
Use in completion signal¶
Graph: {stats["total_nodes"]} nodes, {stats["total_edges"]} edges¶
Source code in src/code_context_agent/tools/graph/tools.py
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 | |
lsp_definition async ¶
Go to definition of symbol at position.
Use this to find where a symbol is defined, useful for tracing dependencies and understanding code structure.
Requires: Call lsp_start first to create a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id | str | Session ID from lsp_start. | required |
file_path | str | Absolute path to the file. | required |
line | int | 0-indexed line number. | required |
character | int | 0-indexed column number. | required |
Returns:
| Type | Description |
|---|---|
str | JSON array of Location objects pointing to definition(s). |
Example
defn = await lsp_definition("ts:/path/repo", "/path/repo/src/index.ts", 5, 12)
Returns: [{"uri": "file:///path/repo/src/utils.ts", "range": {...}}]¶
Source code in src/code_context_agent/tools/lsp/tools.py
lsp_document_symbols async ¶
Get document symbol outline (functions, classes, methods, variables).
USE THIS TOOL: - To get a structural overview of a file without reading full contents - To find function/class names and their line ranges for targeted reading - To understand file organization before diving into implementation - To get accurate symbol positions for lsp_references or lsp_hover calls
DO NOT USE: - Before calling lsp_start (will fail with "No active LSP session") - For searching across multiple files (use rg_search instead) - For simple line counting or file metadata (use read_file_bounded)
Requires: Call lsp_start first to create a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id | str | Session ID from lsp_start (format: "kind:workspace"). | required |
file_path | str | Absolute path to the file to analyze. | required |
Returns:
| Type | Description |
|---|---|
str | JSON with symbols array containing name, kind, range, and nested children. |
Output Size: ~100-500 bytes per symbol. Typical file: 1-5KB response.
Symbol Kinds (common values): - 5: Class - 6: Method - 12: Function - 13: Variable - 14: Constant - 23: Struct
Common Errors
- "No active LSP session": Call lsp_start first
- Empty symbols array: File may not be parseable or have no exports
- "File not found": Ensure file_path is absolute and exists
Example success
{"status": "success", "file": "/repo/src/index.ts", "symbols": [ {"name": "main", "kind": 12, "range": {"start": {"line": 10}}, "children": []} ], "count": 5}
Workflow tip
- Use lsp_document_symbols to find symbol names and line numbers
- Use read_file_bounded with start_line to read specific sections
- Use lsp_references to find where symbols are used
Source code in src/code_context_agent/tools/lsp/tools.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
lsp_hover async ¶
Get hover information at a position (docstrings, JSDoc, type info).
Retrieves documentation and type information for the symbol at the given position. This is how you extract docstrings and JSDoc comments.
Requires: Call lsp_start first to create a session.
Args: session_id: Session ID from lsp_start. file_path: Absolute path to the file. line: 0-indexed line number. character: 0-indexed column number.
Returns: JSON object with hover contents (often includes markdown documentation).
Example: >>> hover = await lsp_hover("ts:/path/repo", "/path/repo/src/utils.ts", 10, 5) >>> # Returns: {"contents": {"kind": "markdown", "value": "/** * Utility function..."}}
Source code in src/code_context_agent/tools/lsp/tools.py
lsp_references async ¶
Find all references to symbol at position (fan-in analysis).
Use this to understand how widely a symbol is used across the codebase. The number of unique referencing files indicates the symbol's centrality.
Requires: Call lsp_start first to create a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id | str | Session ID from lsp_start. | required |
file_path | str | Absolute path to the file. | required |
line | int | 0-indexed line number. | required |
character | int | 0-indexed column number. | required |
include_declaration | bool | Whether to include the declaration itself. | True |
Returns:
| Type | Description |
|---|---|
str | JSON array of Location objects with uri and range. |
Example
refs = await lsp_references("ts:/path/repo", "/path/repo/src/api.ts", 25, 10)
Returns: [{"uri": "file:///path/repo/src/handler.ts", "range": {...}}, ...]¶
Source code in src/code_context_agent/tools/lsp/tools.py
lsp_shutdown async ¶
Shutdown an LSP server session.
Use this when you're done with a workspace to free resources. Sessions are automatically cleaned up when the agent finishes, but explicit shutdown is more efficient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id | str | Session ID from lsp_start. | required |
Returns:
| Type | Description |
|---|---|
str | JSON object with shutdown status. |
Example
await lsp_shutdown("ts:/path/repo")
Returns:¶
Source code in src/code_context_agent/tools/lsp/tools.py
lsp_start async ¶
Start an LSP server and initialize workspace for semantic analysis.
USE THIS TOOL: - Before using any other lsp_* tools (required prerequisite) - Once per language per workspace (session is reused automatically) - When you need semantic analysis: symbols, references, definitions, hover
DO NOT USE: - If you already started an LSP session for this language/workspace combo - For simple text searches (use rg_search instead - much faster) - For repos without the target language (e.g., don't start "ts" for Python-only repo)
Supported server kinds: - "ts": TypeScript/JavaScript (typescript-language-server) - "py": Python (ty server, with pyright-langserver fallback)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_kind | str | Server type - "ts" for TypeScript/JS, "py" for Python. | required |
workspace_path | str | Absolute path to the repository/workspace root. | required |
Returns:
| Type | Description |
|---|---|
str | Session ID (format: "kind:path") for use in subsequent LSP calls. |
Output Size: ~150 bytes JSON response.
Resource Usage
- Memory: 100-500MB per server (depends on project size)
- Startup time: 2-30 seconds (indexing dependent)
- Sessions persist until lsp_shutdown or agent exit
Common Errors
- "typescript-language-server not found": npm install -g typescript-language-server
- "ty not found": uv tool install ty or pip install ty
- Timeout: Large projects may exceed startup_timeout, increase in config
- "No tsconfig.json": TypeScript server needs tsconfig.json in workspace
Example success
{"status": "success", "session_id": "ts:/path/repo", "message": "LSP server started..."}
Workflow
- lsp_start("ts", "/repo") # Start once
- lsp_document_symbols(session_id, file) # Use many times
- lsp_references(session_id, file, line, char)
- lsp_shutdown(session_id) # Optional cleanup
Source code in src/code_context_agent/tools/lsp/tools.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
run_command ¶
Run shell command with bounds.
Uses shell=False with shlex parsing for security. For commands requiring shell features (pipes, redirects), pass a list like ["sh", "-c", "cmd"].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd | str | list[str] | Command string or list of arguments. | required |
cwd | str | None | Working directory. | None |
timeout | int | Maximum execution time in seconds. | 120 |
max_output | int | Maximum characters to capture. | 100000 |
input_data | str | None | Optional string to send to stdin. | None |
Returns:
| Type | Description |
|---|---|
CommandResult | Dict with status, stdout, stderr, return_code, and truncated flag. |
Source code in src/code_context_agent/tools/shell.py
validate_file_path ¶
Validate file path is safe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | User-provided file path. | required |
must_exist | bool | If True, file must exist. | True |
Returns:
| Type | Description |
|---|---|
Path | Resolved Path object. |
Raises:
| Type | Description |
|---|---|
ValidationError | If path is dangerous or invalid. |
Source code in src/code_context_agent/tools/validation.py
validate_glob_pattern ¶
Validate glob pattern is safe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern | str | User-provided glob pattern. | required |
Returns:
| Type | Description |
|---|---|
str | Validated pattern string. |
Raises:
| Type | Description |
|---|---|
ValidationError | If pattern contains dangerous characters. |
Source code in src/code_context_agent/tools/validation.py
validate_path_within_repo ¶
Validate that a path is contained within the repository root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path to validate. | required |
repo_root | str | Repository root path. | required |
Returns:
| Type | Description |
|---|---|
Path | Resolved Path object. |
Raises:
| Type | Description |
|---|---|
ValidationError | If path escapes the repository root. |
Source code in src/code_context_agent/tools/validation.py
validate_repo_path ¶
Validate repository path is safe to use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | User-provided path string. | required |
Returns:
| Type | Description |
|---|---|
Path | Resolved Path object. |
Raises:
| Type | Description |
|---|---|
ValidationError | If path is dangerous or invalid. |
Example
validate_repo_path("/home/user/project") PosixPath('/home/user/project')
Source code in src/code_context_agent/tools/validation.py
validate_search_pattern ¶
Validate search pattern (regex) is safe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern | str | User-provided search pattern. | required |
max_length | int | Maximum allowed pattern length. | 1000 |
Returns:
| Type | Description |
|---|---|
str | Validated pattern string. |
Raises:
| Type | Description |
|---|---|
ValidationError | If pattern is invalid or too long. |