Skip to content

Getting Started with Code2Prompt

Tutorial Overview

Welcome to Code2Prompt! This tutorial provides a comprehensive introduction to using Code2Prompt to generate AI-ready prompts from your codebases. We’ll explore its core functionality and demonstrate its usage across different integration methods: Command Line Interface (CLI), Software Development Kit (SDK), and Model Context Protocol (MCP).

Code2Prompt is a versatile tool designed to bridge the gap between your codebase and Large Language Models (LLMs). It intelligently extracts relevant code snippets, applies powerful filtering, and formats the information into structured prompts optimized for LLM consumption. This simplifies tasks like code documentation, bug detection, refactoring, and more.

Code2Prompt offers different integration points:

A core rust library that provides the foundation for code ingestion and prompt

For detailed installation instructions for all methods (CLI, SDK, MCP), please refer to the comprehensive Installation Guide.

Let’s start with a simple example using the CLI. Create a sample project:

Terminal window
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

Now, generate a prompt:

Terminal window
code2prompt my_project

This copies a prompt to your clipboard. You can customize this:

  • Filtering: code2prompt my_project --include="*.rs" --exclude="tests/*" (includes only .rs files, excludes tests directory)
  • Output File: code2prompt my_project --output-file=my_prompt.txt
  • JSON Output: code2prompt my_project -O json (structured JSON output)
  • Custom Templates: code2prompt my_project -t my_template.hbs (requires creating my_template.hbs)

See the Learn Context Filtering and Learn Handlebar Templates tutorials to learn more advanced usages.

For programmatic control, use the Python SDK:

from code2prompt_rs import Code2Prompt
config = {
"path": "my_project",
"include_patterns": ["*.rs"],
"exclude_patterns": ["tests/*"],
}
c2p = Code2Prompt(**config)
prompt = c2p.generate_prompt()
print(prompt)

This requires installing the SDK (pip install code2prompt_rs). Refer to the SDK documentation for more details.

For advanced integration with LLM agents, run the code2prompt MCP server (see the installation guide for details). This allows agents to request code context dynamically. This is an advanced feature, and further documentation is available on the project’s website.

Next Steps

Explore the advanced tutorials and documentation to master Code2Prompt’s capabilities and integrate it into your workflows.